using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ICP_MS.Plugin.Experiment.Forms;

namespace ICP_MS.Plugin.Experiment;

public class ExperimentDatas
{
	public bool IsFirst = false;

	public bool bUseAbnormalMethod = false;

	public bool bUseDeductBkg = false;

	public int UsePA = 0;

	public bool switchPA = false;

	public bool bUseAutoMisfire = false;

	public AutoResetEvent[] dataprocessEvent = new AutoResetEvent[3]
	{
		new AutoResetEvent(initialState: false),
		new AutoResetEvent(initialState: false),
		new AutoResetEvent(initialState: false)
	};

	public bool bUptakeAndStableFinished = false;

	private List<AnalyteIsotope> selectIsotopes = new List<AnalyteIsotope>();

	private IList<ScanRegions> surveyRegions = new List<ScanRegions>();

	private IList<ScanRegions> scanRegions = new List<ScanRegions>();

	private List<PeakRegions> peakRegions = new List<PeakRegions>();

	private List<IsotopeInfos> isotopes = new List<IsotopeInfos>();

	private List<IsotopeRatio> ratios = new List<IsotopeRatio>();

	private List<SamplesInfos> samples = new List<SamplesInfos>();

	private List<StandardConcentration> stdConcentration = new List<StandardConcentration>();

	private List<QCSConcentration> qcsConcentration = new List<QCSConcentration>();

	private List<AnalyseInfos> results = new List<AnalyseInfos>();

	private List<StatisticResults> statistics = new List<StatisticResults>();

	private List<RatioResults> ratioResults = new List<RatioResults>();

	private List<RatioStatistics> ratioStat = new List<RatioStatistics>();

	private List<SpectrumInfos> spectrums = new List<SpectrumInfos>();

	private List<IsotopeCurve> curves = new List<IsotopeCurve>();

	private ReportParams reportParams = new ReportParams
	{
		ShowRuns = true,
		ShowMean = true,
		ShowSd = true,
		ShowRsd = true,
		ShowConc = true,
		ShowCPS = true,
		ShowUCPS = true,
		ShowCurve = true,
		Header = "",
		Title = "",
		ShowAssignment = false,
		Logo = null
	};

	private ScanParams scanParams = new ScanParams();

	private QCSPara qcsPara = new QCSPara();

	private IList<PointF> disallowedRanges = new List<PointF>();

	private AutoResetEvent scanEvent = new AutoResetEvent(initialState: false);

	public bool bStableFunEnd = false;

	private string internalSchema = "Default";

	private bool isInCalculate = false;

	private DirtyInfo dirty = new DirtyInfo();

	private double[] surveyMass = null;

	private double[] scanMass = null;

	private double[] peakMass = null;

	private int[] resolutionType = null;

	private double[] dwelltimes = null;

	private List<double> OutPeakMass = new List<double>();

	private List<double> OutPeakMassBuffer = new List<double>();

	public Platform CurrentPlat { get; set; }

	public X2Lens CurrentLens { get; set; }

	public PlasmaPara CurrentPlasma { get; set; }

	public RFS CurrentRFS { get; set; }

	public Injector CurrentInjector { get; set; }

	public AutoSampleTable AutosampleTable { get; set; }

	public StableConfig StableConfig { get; set; }

	public SamplesInfos CurrentSample { get; set; }

	public List<BlankCalibration> BlankCalibration { get; set; }

	public List<AnalyteIsotope> SelectIsotopes
	{
		get
		{
			return selectIsotopes;
		}
		set
		{
			selectIsotopes = value;
		}
	}

	public IList<ScanRegions> SurveyRegions
	{
		get
		{
			return surveyRegions;
		}
		set
		{
			surveyRegions = value;
		}
	}

	public IList<ScanRegions> ScanRegions
	{
		get
		{
			return scanRegions;
		}
		set
		{
			scanRegions = value;
		}
	}

	public List<PeakRegions> PeakRegions
	{
		get
		{
			return peakRegions;
		}
		set
		{
			peakRegions = value;
		}
	}

	public List<IsotopeInfos> Isotopes
	{
		get
		{
			return isotopes;
		}
		set
		{
			isotopes = value;
		}
	}

	public List<IsotopeRatio> Ratios
	{
		get
		{
			return ratios;
		}
		set
		{
			ratios = value;
		}
	}

	public List<SamplesInfos> Samples
	{
		get
		{
			return samples;
		}
		set
		{
			samples = value;
		}
	}

	public List<StandardConcentration> StdConcentration
	{
		get
		{
			return stdConcentration;
		}
		set
		{
			stdConcentration = value;
		}
	}

	public List<QCSConcentration> QCSConcentration
	{
		get
		{
			return qcsConcentration;
		}
		set
		{
			qcsConcentration = value;
		}
	}

	public List<AnalyseInfos> Results
	{
		get
		{
			return results;
		}
		set
		{
			results = value;
		}
	}

	public List<StatisticResults> Statistics
	{
		get
		{
			return statistics;
		}
		set
		{
			statistics = value;
		}
	}

	public List<RatioResults> RatioResults
	{
		get
		{
			return ratioResults;
		}
		set
		{
			ratioResults = value;
		}
	}

	public List<RatioStatistics> RatioStat
	{
		get
		{
			return ratioStat;
		}
		set
		{
			ratioStat = value;
		}
	}

	public List<SpectrumInfos> Spectrums
	{
		get
		{
			return spectrums;
		}
		set
		{
			spectrums = value;
		}
	}

	public List<IsotopeCurve> Curves
	{
		get
		{
			return curves;
		}
		set
		{
			curves = value;
		}
	}

	public ReportParams ReportParams
	{
		get
		{
			return reportParams;
		}
		set
		{
			reportParams = value;
		}
	}

	public ScanParams Scan
	{
		get
		{
			return scanParams;
		}
		set
		{
			scanParams = value;
		}
	}

	public QCSPara QCS
	{
		get
		{
			return qcsPara;
		}
		set
		{
			qcsPara = value;
		}
	}

	public IList<PointF> DisallowedRanges => disallowedRanges;

	public string InternalSchema
	{
		get
		{
			return internalSchema;
		}
		set
		{
			internalSchema = value;
		}
	}

	public DirtyInfo Dirty => dirty;

	public bool IsRun { get; set; }

	public event EventHandler<ExperimentEventArgs> EventExperiment = null;

	public event EventHandler applyEnable = null;

	public event EventHandler refreshChanged = null;

	public event EventHandler SeqSampleChanged = null;

	public event EventHandler isotopeChanged = null;

	public event EventHandler ratioChanged = null;

	public event EventHandler istdChanged = null;

	public event EventHandler IsAutoSamplerChangedEvent = null;

	public event EventHandler sampleChanged = null;

	public event EventHandler sampleselfChanged = null;

	public event EventHandler methodChanged = null;

	public static event EventHandler autoMisfire;

	private void SortIsotopes()
	{
		Isotopes.Sort((IsotopeInfos isotope1, IsotopeInfos isotope2) => isotope1.mass.CompareTo(isotope2.mass));
	}

	public void SetupIsotopeInfos()
	{
		Isotopes.RemoveAll((IsotopeInfos isotope) => !SelectIsotopes.Exists((AnalyteIsotope selectIsotope) => selectIsotope.symbol == isotope.symbol));
		SelectIsotopes.ForEach(delegate(AnalyteIsotope selectIsotope)
		{
			if (!Isotopes.Exists((IsotopeInfos isotope) => isotope.symbol == selectIsotope.symbol))
			{
				Isotopes.Add(new IsotopeInfos
				{
					id = selectIsotope.id,
					symbol = selectIsotope.symbol,
					mass = selectIsotope.mass,
					name = "Default",
					units = "ng/mL",
					visible = true,
					technique = Lang.Txt("FormStandard.Istd.Technique.None.Text"),
					force = 0,
					withInterference = selectIsotope.withInterference,
					isInterference = false,
					PASlope = Detector.Instance.dacPAFactors[(int)(selectIsotope.mass * 100.0)],
					PAIntercept = 0.0
				});
			}
			else
			{
				IsotopeInfos isotopeInfos = Isotopes.Find((IsotopeInfos isotope) => isotope.symbol == selectIsotope.symbol);
				isotopeInfos.isInterference = false;
			}
		});
		Dirty.IsotopeInfoDirty = true;
	}

	public void UpdateResultsBySampleId(SamplesInfos sample)
	{
		Results.RemoveAll((AnalyseInfos r) => r.sampleId == sample.guid);
		Statistics.RemoveAll((StatisticResults r) => r.sampleId == sample.guid);
		foreach (IsotopeInfos isotope in Isotopes)
		{
			for (int num = 0; num < sample.mains; num++)
			{
				Results.Add(new AnalyseInfos
				{
					isotopeId = isotope.id,
					symbol = isotope.symbol,
					sampleId = sample.guid,
					label = sample.label,
					number = num,
					test = false,
					intensity = -1.0,
					concentration = -1.0,
					icps = -1.0
				});
			}
			Statistics.Add(new StatisticResults
			{
				isotopeId = isotope.id,
				symbol = isotope.symbol,
				sampleId = sample.guid,
				label = sample.label,
				mass = sample.mass,
				volume = sample.volume,
				avgCon = -1.0,
				avgUICPS = -1.0,
				avgCPS = -1.0,
				sdCon = -1.0,
				sdUICPS = -1.0,
				sdCPS = -1.0,
				rsdCon = -1.0,
				rsdUICPS = -1.0,
				rsdCPS = -1.0,
				include = true
			});
		}
	}

	public void SetupResultsBySample()
	{
		IEnumerable<int> sampleIds = Samples.Select((SamplesInfos sample) => sample.guid);
		Results.RemoveAll((AnalyseInfos r) => !sampleIds.Contains(r.sampleId));
		Statistics.RemoveAll((StatisticResults r) => !sampleIds.Contains(r.sampleId));
		RatioResults.RemoveAll((RatioResults r) => !sampleIds.Contains(r.SampleId));
		RatioStat.RemoveAll((RatioStatistics r) => !sampleIds.Contains(r.SampleId));
		IEnumerable<int> r_sampleId = Results.Select((AnalyseInfos result) => result.sampleId);
		foreach (SamplesInfos sample2 in Samples)
		{
			if (r_sampleId.Contains(sample2.guid))
			{
				continue;
			}
			foreach (IsotopeInfos isotope2 in Isotopes)
			{
				for (int num2 = 0; num2 < sample2.mains; num2++)
				{
					Results.Add(new AnalyseInfos
					{
						isotopeId = isotope2.id,
						symbol = isotope2.symbol,
						sampleId = sample2.guid,
						label = sample2.label,
						number = num2,
						test = false,
						intensity = -1.0,
						concentration = -1.0,
						icps = -1.0
					});
				}
				Statistics.Add(new StatisticResults
				{
					isotopeId = isotope2.id,
					symbol = isotope2.symbol,
					sampleId = sample2.guid,
					label = sample2.label,
					avgCon = -1.0,
					avgUICPS = -1.0,
					avgCPS = -1.0,
					sdCon = -1.0,
					sdUICPS = -1.0,
					sdCPS = -1.0,
					rsdCon = -1.0,
					rsdUICPS = -1.0,
					rsdCPS = -1.0,
					include = true
				});
			}
			foreach (IsotopeRatio isotope in Ratios)
			{
				ratioStat.Add(new RatioStatistics
				{
					Name = isotope.Name,
					Numerator = isotope.NumeratorSym,
					Denominator = isotope.DenominatorSym,
					SampleId = sample2.guid,
					Label = sample2.label,
					Sd = -1.0,
					Rsd = -1.0,
					Avg = -1.0
				});
				for (int num = 0; num < sample2.mains; num++)
				{
					ratioResults.Add(new RatioResults
					{
						Name = isotope.Name,
						Numerator = isotope.NumeratorSym,
						Denominator = isotope.DenominatorSym,
						SampleId = sample2.guid,
						Label = sample2.label,
						Number = num,
						Result = -1.0
					});
				}
			}
		}
	}

	public string ExportStrAlpha(string symbol)
	{
		return Regex.Replace(symbol, "[0-9]", "", RegexOptions.IgnoreCase);
	}

	public void FillStdConcentration()
	{
		StdConcentration.RemoveAll((StandardConcentration std) => !Samples.Exists((SamplesInfos sample) => sample.guid == std.sample) || !Isotopes.Exists((IsotopeInfos isotope) => isotope.symbol.Contains(std.symbol)));
		StdConcentration.RemoveAll((StandardConcentration std) => Samples.Exists((SamplesInfos sample) => sample.guid == std.sample && (sample.type == 0 || sample.type == 3 || sample.type == 4)));
		foreach (SamplesInfos sample3 in Samples)
		{
			if (sample3.type != 1 && sample3.type != 2 && sample3.type != 5)
			{
				continue;
			}
			foreach (IsotopeInfos isotope3 in Isotopes)
			{
				if (!StdConcentration.Exists((StandardConcentration std) => std.sample == sample3.guid && ExportStrAlpha(isotope3.symbol).Equals(std.symbol)))
				{
					StandardConcentration standard = new StandardConcentration
					{
						label = sample3.label,
						symbol = Regex.Replace(isotope3.symbol, "[0-9]", "", RegexOptions.IgnoreCase),
						inter = isotope3.inter,
						sample = sample3.guid,
						concentration = -1.0,
						method = isotope3.method
					};
					StdConcentration.Add(standard);
				}
			}
		}
		qcsConcentration.RemoveAll((QCSConcentration qcs) => !Samples.Exists((SamplesInfos sample) => sample.guid == qcs.sample) || !Isotopes.Exists((IsotopeInfos isotope) => isotope.symbol == qcs.symbol));
		qcsConcentration.RemoveAll((QCSConcentration std) => Samples.Exists((SamplesInfos sample) => sample.guid == std.sample && sample.type != 4));
		foreach (SamplesInfos sample2 in Samples)
		{
			if (sample2.type != 4)
			{
				continue;
			}
			foreach (IsotopeInfos isotope2 in isotopes)
			{
				if (!QCSConcentration.Exists((QCSConcentration qcs) => qcs.sample == sample2.guid && qcs.symbol == isotope2.symbol))
				{
					QCSConcentration qcs2 = new QCSConcentration
					{
						label = sample2.label,
						symbol = isotope2.symbol,
						unit = 2,
						sample = sample2.guid,
						concentration = -1.0,
						lowlimit = 0.0,
						highlimit = 0.0
					};
					QCSConcentration.Add(qcs2);
				}
			}
		}
	}

	public void SetupRatioResults()
	{
		IEnumerable<string> names = Ratios.Select((IsotopeRatio isotope) => isotope.Name);
		ratioResults.RemoveAll((RatioResults r) => !names.Contains(r.Name));
		RatioStat.RemoveAll((RatioStatistics r) => !names.Contains(r.Name));
		IEnumerable<string> r_names = ratioResults.Select((RatioResults result) => result.Name);
		foreach (IsotopeRatio isotope2 in Ratios)
		{
			if (r_names.Contains(isotope2.Name))
			{
				continue;
			}
			foreach (SamplesInfos sample in Samples)
			{
				ratioStat.Add(new RatioStatistics
				{
					Name = isotope2.Name,
					Numerator = isotope2.NumeratorSym,
					Denominator = isotope2.DenominatorSym,
					SampleId = sample.guid,
					Label = sample.label,
					Sd = -1.0,
					Rsd = -1.0,
					Avg = -1.0
				});
				for (int num = 0; num < sample.mains; num++)
				{
					ratioResults.Add(new RatioResults
					{
						Name = isotope2.Name,
						Numerator = isotope2.NumeratorSym,
						Denominator = isotope2.DenominatorSym,
						SampleId = sample.guid,
						Label = sample.label,
						Number = num,
						Result = -1.0
					});
				}
			}
		}
	}

	private void SetPeakJumpRegions()
	{
		List<PeakRegions> removeregions = new List<PeakRegions>();
		foreach (PeakRegions peakregion2 in PeakRegions)
		{
			if (Isotopes.Find((IsotopeInfos isotope) => isotope.mass == peakregion2.mass) == null)
			{
				removeregions.Add(peakregion2);
			}
		}
		for (int i = 0; i < removeregions.Count; i++)
		{
			PeakRegions.Remove(removeregions[i]);
		}
		foreach (IsotopeInfos isotope2 in Isotopes)
		{
			if (PeakRegions.Find((PeakRegions peakregion) => peakregion.symbol == isotope2.symbol) == null)
			{
				if (PeakRegions.Count > 0)
				{
					PeakRegions.Add(new PeakRegions(isotope2.symbol, isotope2.mass, PeakRegions[0].dwell, PeakRegions[0].channels));
				}
				else
				{
					PeakRegions.Add(new PeakRegions(isotope2.symbol, isotope2.mass));
				}
			}
		}
		PeakRegions.Sort((PeakRegions a, PeakRegions b) => a.mass.CompareTo(b.mass));
	}

	private void AddFixedScanRegions()
	{
		ScanRegions.Clear();
		foreach (IsotopeInfos isotope in Isotopes)
		{
			ScanRegions.Add(new ScanRegions(isotope.mass - 0.1, isotope.mass + 0.1, "Scan"));
		}
	}

	private void SetSurveyRegions()
	{
		SurveyRegions.Add(new ScanRegions(0.0, 255.0, "Survey"));
	}

	private void InitScan()
	{
		SetPeakJumpRegions();
		AddFixedScanRegions();
		if (isotopes == null || isotopes.Count <= 0)
		{
			ScanParams scan = Scan;
			bool isPeakjump = (Scan.isScan = false);
			scan.isPeakjump = isPeakjump;
		}
	}

	private bool InitRunMass()
	{
		InitScan();
		if (Scan.isSurvey)
		{
			List<double> tmp = new List<double>();
			foreach (ScanRegions region in SurveyRegions)
			{
				for (double mass = region.start; mass <= region.end; mass += 1.0 / (double)region.channels)
				{
					bool bInDisallowed = false;
					foreach (PointF pt in disallowedRanges)
					{
						if (mass >= (double)pt.X && mass <= (double)pt.Y)
						{
							bInDisallowed = true;
							break;
						}
					}
					if (!bInDisallowed)
					{
						tmp.Add(mass);
					}
				}
				RFManager.rfs.dwell = region.dwell;
			}
			Detector.Instance.msDetectorRF.SetDwell();
			surveyMass = tmp.ToArray();
		}
		if (Scan.isScan)
		{
			List<double> tmp3 = new List<double>();
			foreach (ScanRegions region3 in ScanRegions)
			{
				for (double mass2 = region3.start; mass2 <= region3.end; mass2 += 1.0 / (double)region3.channels)
				{
					tmp3.Add(mass2);
				}
				RFManager.rfs.dwell = region3.dwell;
			}
			Detector.Instance.msDetectorRF.SetDwell();
			scanMass = tmp3.ToArray();
		}
		if (Scan.isPeakjump)
		{
			List<double> tmp2 = new List<double>();
			List<int> resolution = new List<int>();
			List<double> dwelltime = new List<double>();
			foreach (PeakRegions region2 in PeakRegions)
			{
				for (int i = -region2.channels / 2; i <= region2.channels / 2; i++)
				{
					tmp2.Add(region2.mass + (double)i * region2.separation);
					dwelltime.Add(region2.dwell);
					resolution.Add((region2.resolution == Lang.Txt("FormScanLA.Standard")) ? 1 : ((!(region2.resolution == "高")) ? 2 : 0));
				}
				RFManager.rfs.dwell = region2.dwell;
			}
			Detector.Instance.msDetectorRF.SetDwell();
			peakMass = tmp2.ToArray();
			dwelltimes = dwelltime.ToArray();
			resolutionType = resolution.ToArray();
		}
		if ((peakMass != null && peakMass.Count() > 0) || (scanMass != null && scanMass.Count() > 0) || (surveyMass != null && surveyMass.Count() > 0))
		{
			return true;
		}
		return false;
	}

	private void InitCurve()
	{
		foreach (IsotopeInfos isotope in Isotopes)
		{
			int id;
			for (id = 1; id <= 10; id++)
			{
				if (!Curves.Exists((IsotopeCurve curve) => isotope.symbol == curve.symbol && id == curve.groupId))
				{
					Curves.Add(new IsotopeCurve
					{
						isotopeId = isotope.id,
						symbol = isotope.symbol,
						k = 1.0,
						b = 0.0,
						r = 1.0,
						intercept1 = 0.0,
						intercept2 = 0.0,
						calculated = false,
						groupId = id
					});
				}
			}
		}
	}

	private void InitResult(SamplesInfos sample)
	{
		Results.RemoveAll((AnalyseInfos result) => result.sampleId == sample.guid);
		Statistics.RemoveAll((StatisticResults result) => result.sampleId == sample.guid);
		foreach (IsotopeInfos isotope2 in Isotopes)
		{
			for (int num2 = 0; num2 < sample.mains; num2++)
			{
				Results.Add(new AnalyseInfos
				{
					isotopeId = isotope2.id,
					symbol = isotope2.symbol,
					sampleId = sample.guid,
					label = sample.label,
					number = num2,
					test = false,
					intensity = -1.0,
					concentration = -1.0,
					icps = -1.0
				});
			}
			Statistics.Add(new StatisticResults
			{
				isotopeId = isotope2.id,
				symbol = isotope2.symbol,
				sampleId = sample.guid,
				label = sample.label,
				mass = sample.mass,
				volume = sample.volume,
				avgCon = -1.0,
				avgUICPS = -1.0,
				avgCPS = -1.0,
				sdCon = -1.0,
				sdUICPS = -1.0,
				sdCPS = -1.0,
				rsdCon = -1.0,
				rsdUICPS = -1.0,
				rsdCPS = -1.0,
				include = true
			});
		}
		RatioResults.RemoveAll((RatioResults ratio) => ratio.SampleId == sample.guid);
		RatioStat.RemoveAll((RatioStatistics ratio) => ratio.SampleId == sample.guid);
		foreach (IsotopeRatio isotope in Ratios)
		{
			ratioStat.Add(new RatioStatistics
			{
				Name = isotope.Name,
				Numerator = isotope.NumeratorSym,
				Denominator = isotope.DenominatorSym,
				SampleId = sample.guid,
				Label = sample.label,
				Sd = -1.0,
				Rsd = -1.0,
				Avg = -1.0
			});
			for (int num = 0; num < sample.mains; num++)
			{
				ratioResults.Add(new RatioResults
				{
					Name = isotope.Name,
					Numerator = isotope.NumeratorSym,
					Denominator = isotope.DenominatorSym,
					SampleId = sample.guid,
					Label = sample.label,
					Number = num,
					Result = -1.0
				});
			}
		}
	}

	private void InitSpectrum(SamplesInfos sample)
	{
		Spectrums.RemoveAll((SpectrumInfos spectrum) => spectrum.sampleId == sample.guid);
		if (Scan.isSurvey)
		{
			for (int k = 0; k < sample.surveys; k++)
			{
				Spectrums.Add(new SpectrumInfos
				{
					sampleId = sample.guid,
					label = sample.label,
					scanType = 0,
					scanIndex = k,
					isTest = false
				});
			}
		}
		if (Scan.isScan)
		{
			for (int j = 0; j < sample.mains; j++)
			{
				Spectrums.Add(new SpectrumInfos
				{
					sampleId = sample.guid,
					label = sample.label,
					scanType = 1,
					scanIndex = j,
					isTest = false
				});
			}
		}
		if (Scan.isPeakjump)
		{
			for (int i = 0; i < sample.mains; i++)
			{
				Spectrums.Add(new SpectrumInfos
				{
					sampleId = sample.guid,
					label = sample.label,
					scanType = 2,
					scanIndex = i,
					isTest = false
				});
			}
		}
	}

	public bool PreRun()
	{
		if (!InitRunMass())
		{
			MessageBox.Show("请检查是否选择了分析元素，或者选中了扫描模式", "提示", MessageBoxButtons.OK);
			return false;
		}
		return true;
	}

	public void SeqSampleAddNotify()
	{
		if (this.SeqSampleChanged != null)
		{
			this.SeqSampleChanged(null, null);
		}
	}

	public void StartRun()
	{
		if (AutosampleTable.autoSample && !AutoSampler.Instance.Init())
		{
			MessageBox.Show("请连接自动进样器！", "提示", MessageBoxButtons.OK);
			return;
		}
		InitCurve();
		Detector.Instance.ExperimentState = 5;
		IsRun = true;
		Detector.finishReceive += Detector_massFinishReceive;
		Detector.errorReceive += Detector_errorReceive;
		Detector.errorevent += Detector_errorevent;
		Scan.currentStatus = 1;
		LensManager.x2lens = CurrentLens.Clone();
		LensManager.Instance.X2_SetAll();
		int statusPlasma = PlasmaManager.plasma.StatusPlasma;
		PlasmaManager.plasma = CurrentPlasma.Clone();
		PlasmaManager.plasma.StatusPlasma = statusPlasma;
		Plasma.Instance.OpenCoolGas();
		Plasma.Instance.OpenNebulizerGas();
		Plasma.Instance.SetPower();
		if (Collision.Instance.CRCType == 1)
		{
			Plasma.Instance.OpenCollision();
		}
		else
		{
			Plasma.Instance.OpenCollision();
			Plasma.Instance.OpenCollision2();
		}
		Plasma.Instance.OpenAppendixGas();
		double dwell = RFManager.rfs.dwell;
		RFManager.rfs = CurrentRFS.CloneWithoutDwell();
		RFManager.rfs.dwell = dwell;
		Detector.Instance.msDetectorRF.SetSuspend(false);
		Detector.Instance.msDetectorRF.SetStable();
		if (Detector.detectorConfig.IsNewDetector)
		{
			Detector.Instance.msDetectorRF.SetHVNNew();
			Detector.Instance.msDetectorRF.SetHVPNew();
			Detector.Instance.msDetectorRF.SetGateNew();
			Detector.Instance.msDetectorRF.SetQuadPoleNew();
			Detector.Instance.msDetectorRF.SetPrePoleNew();
		}
		else
		{
			Detector.Instance.msDetectorRF.SetHVN();
			Detector.Instance.msDetectorRF.SetHVP();
			Detector.Instance.msDetectorRF.SetGate();
			Detector.Instance.msDetectorRF.SetQuadPole();
			Detector.Instance.msDetectorRF.SetPrePole();
		}
		PlatManager.plat = CurrentPlat.Clone();
		Plasma.Instance.SetPlatform();
		PlatManager.Instrumentinjector.Perist = CurrentInjector.Clone().Perist;
		Plasma.Instance.SetPeristaltic(PlatManager.Instrumentinjector.Perist);
		if (this.applyEnable != null)
		{
			this.applyEnable(this, null);
		}
		Task.Factory.StartNew(RunExperiment);
	}

	private void Detector_errorevent(object sender, EventArgs e)
	{
		StopRun();
	}

	public int StartRun(SamplesInfos sample)
	{
		if (AutosampleTable.autoSample && !AutoSampler.Instance.Init())
		{
			MessageBox.Show("请连接自动进样器！", "提示", MessageBoxButtons.OK);
			return -1;
		}
		InitCurve();
		Detector.Instance.ExperimentState = 5;
		IsRun = true;
		Detector.finishReceive += Detector_massFinishReceive;
		Detector.errorReceive += Detector_errorReceive;
		Scan.currentStatus = 1;
		if (this.applyEnable != null)
		{
			this.applyEnable(this, null);
		}
		Task.Factory.StartNew(delegate
		{
			LensManager.x2lens = CurrentLens.Clone();
			LensManager.Instance.X2_SetAll();
			LensManager.Instance.SetEtp();
			PlasmaManager.plasma = CurrentPlasma.Clone();
			Plasma.Instance.OpenCoolGas();
			Plasma.Instance.OpenNebulizerGas();
			Plasma.Instance.SetPower();
			if (Collision.Instance.CRCType == 1)
			{
				Plasma.Instance.OpenCollision();
			}
			else
			{
				Plasma.Instance.OpenCollision();
				Plasma.Instance.OpenCollision2();
			}
			double dwell = RFManager.rfs.dwell;
			RFManager.rfs = CurrentRFS.CloneWithoutDwell();
			RFManager.rfs.dwell = dwell;
			Detector.Instance.msDetectorRF.SetSuspend(false);
			Detector.Instance.msDetectorRF.SetStable();
			if (Detector.detectorConfig.IsNewDetector)
			{
				Detector.Instance.msDetectorRF.SetQuadPoleNew();
				Detector.Instance.msDetectorRF.SetPrePoleNew();
				Detector.Instance.msDetectorRF.SetHVNNew();
				Thread.Sleep(1);
				Detector.Instance.msDetectorRF.SetHVPNew();
				Thread.Sleep(1);
				Detector.Instance.msDetectorRF.SetGateNew();
				Thread.Sleep(1);
			}
			else
			{
				Detector.Instance.msDetectorRF.SetQuadPole();
				Detector.Instance.msDetectorRF.SetPrePole();
				Detector.Instance.msDetectorRF.SetHVN();
				Thread.Sleep(1);
				Detector.Instance.msDetectorRF.SetHVP();
				Thread.Sleep(1);
				Detector.Instance.msDetectorRF.SetGate();
				Thread.Sleep(1);
			}
			Detector.Instance.msDetectorRF.SendVersion();
			PlatManager.Instrumentinjector.Perist = CurrentInjector.Clone().Perist;
			Plasma.Instance.SetPeristaltic(PlatManager.Instrumentinjector.Perist);
			PlatManager.plat = CurrentPlat.Clone();
			Plasma.Instance.SetPlatform();
		});
		return RunExperiment(sample);
	}

	private void Detector_errorReceive(object sender, ErrorMsgEventArgs e)
	{
		if (!OutPeakMass.Contains(e.X) && !OutPeakMassBuffer.Contains(e.X))
		{
			OutPeakMassBuffer.Add(e.X);
		}
	}

	public void StopRun(bool stopApply = true)
	{
		if (!IsRun)
		{
			return;
		}
		scanEvent.Set();
		IsRun = false;
		Detector.finishReceive -= Detector_massFinishReceive;
		Detector.errorReceive -= Detector_errorReceive;
		Detector.errorevent -= Detector_errorevent;
		Detector.Instance.Stop();
		if (stopApply)
		{
			Scan.currentStatus = 2;
		}
		else
		{
			Scan.currentStatus = 3;
		}
		Detector.Instance.ExperimentState = -1;
		if (AutosampleTable.autoSample || CurrentInjector.Wash)
		{
			AutoSampler.Instance.Rinse();
			if (Scan.currentStatus == 3)
			{
				Task.Factory.StartNew(delegate
				{
					CountDown();
				});
			}
			else
			{
				AutoSampler.Instance.Deinit();
			}
		}
		AutoSampler.Instance.IsAutoSampler = false;
		if (AutoSampler.IsAutoSamplerChangedEvent != null)
		{
			AutoSampler.IsAutoSamplerChangedEvent(null, null);
		}
	}

	public static void CountDown()
	{
		for (int secondsLeft = PlatManager.injector.AutoWashTime; secondsLeft > 0; secondsLeft--)
		{
			Thread.Sleep(TimeSpan.FromMinutes(1.0));
		}
		AutoSampler.Instance.Home();
		AutoSampler.Instance.Deinit();
	}

	public int RunExperiment(SamplesInfos sample)
	{
		bUptakeAndStableFinished = false;
		bool acqError = false;
		scanEvent.Reset();
		OutPeakMass.Clear();
		OutPeakMassBuffer.Clear();
		if (PlasmaManager.plasma.StatusPlasma != 7)
		{
			MessageBox.Show("意外熄火或未点火，请在等离子体形成后开始测试！", "提示");
			return -2;
		}
		if (AutosampleTable.autoSample)
		{
			if (!AutoSampler.Instance.IsOpenState)
			{
				MessageBox.Show("自动进样器未连接，请检查！", "提示", MessageBoxButtons.OK);
				return -1;
			}
			AutoSampler.Instance.IsAutoSampler = true;
			if (AutoSampler.IsAutoSamplerChangedEvent != null)
			{
				AutoSampler.IsAutoSamplerChangedEvent(null, null);
			}
		}
		ExperimentPrepare(sample);
		if (Scan.isSurvey)
		{
			acqError = (Detector.detectorConfig.IsNewBoard ? (!ExperimentSurveyRunForNew(sample)) : (!ExperimentSurveyRun(sample)));
			if (acqError)
			{
				return -3;
			}
		}
		if (Scan.isScan || Scan.isPeakjump)
		{
			acqError = (Detector.detectorConfig.IsNewBoard ? (!ExperimentMainRunForNew(sample)) : (!ExperimentMainRun(sample)));
			if (acqError)
			{
				return -3;
			}
		}
		sample.status = 1;
		if (sample.type == 4)
		{
			CheckQCSValues(sample);
		}
		if (this.EventExperiment != null)
		{
			this.EventExperiment(null, new ExperimentEventArgs(sample, 5, 0, 0));
		}
		scanEvent.Set();
		IsRun = false;
		Detector.finishReceive -= Detector_massFinishReceive;
		Detector.errorReceive -= Detector_errorReceive;
		Detector.Instance.Stop();
		Scan.currentStatus = 3;
		Detector.Instance.ExperimentState = -1;
		if (this.EventExperiment != null)
		{
			this.EventExperiment(null, new ExperimentEventArgs(null, acqError ? (-1) : 3, 0, 0));
		}
		return 0;
	}

	public void RunExperiment()
	{
		bUptakeAndStableFinished = false;
		bool acqError = false;
		scanEvent.Reset();
		while (IsRun)
		{
			OutPeakMass.Clear();
			OutPeakMassBuffer.Clear();
			IEnumerable<SamplesInfos> ss = Samples.Where((SamplesInfos s) => s.status != 1 && (!AutosampleTable.autoSample || (AutosampleTable.autoSample && s.vialNumber != -1 && s.rackNumber != -1 && s.ZDepth != "")));
			if (ss.Count() > 0)
			{
				if (!IsRun)
				{
					break;
				}
				if (PlasmaManager.plasma.StatusPlasma != 7)
				{
					Log.InsertLog("测试流程", "停止测试", "等离子体状态异常", (Severity)3);
					break;
				}
				SamplesInfos currentSample = ss.First();
				if (AutosampleTable.autoSample)
				{
					if (!AutoSampler.Instance.IsOpenState)
					{
						MessageBox.Show("自动进样器未连接，请检查！", "提示", MessageBoxButtons.OK);
						break;
					}
					AutoSampler.Instance.IsAutoSampler = true;
					if (AutoSampler.IsAutoSamplerChangedEvent != null)
					{
						AutoSampler.IsAutoSamplerChangedEvent(null, null);
					}
				}
				ExperimentPrepare(currentSample);
				if (!IsRun)
				{
					break;
				}
				if (Scan.isSurvey)
				{
					acqError = (Detector.detectorConfig.IsNewBoard ? (!ExperimentSurveyRunForNew(currentSample)) : (!ExperimentSurveyRun(currentSample)));
					if (acqError)
					{
						break;
					}
				}
				if (!IsRun)
				{
					break;
				}
				if (Scan.isScan || Scan.isPeakjump)
				{
					acqError = (Detector.detectorConfig.IsNewBoard ? (!ExperimentMainRunForNew(currentSample)) : (!ExperimentMainRun(currentSample)));
					if (acqError)
					{
						break;
					}
				}
				currentSample.status = 1;
				if (currentSample.type == 4)
				{
					CheckQCSValues(currentSample);
				}
				if (this.EventExperiment != null)
				{
					this.EventExperiment(null, new ExperimentEventArgs(currentSample, 5, 0, 0));
				}
				continue;
			}
			StopRun(stopApply: false);
			if (bUseAutoMisfire && AutosampleTable.autoSample && Scan.currentStatus == 3)
			{
				string message = "仪器将在10s后进行自动熄火！";
				int second = 10;
				TimingMessageBox messageBox = new TimingMessageBox(message, second);
				if (messageBox.ShowDialog() != DialogResult.Cancel && ExperimentDatas.autoMisfire != null)
				{
					ExperimentDatas.autoMisfire(null, null);
				}
			}
		}
		StopRun();
		if (this.EventExperiment != null)
		{
			this.EventExperiment(null, new ExperimentEventArgs(null, acqError ? (-1) : 3, 0, 0));
		}
		if (PlasmaManager.plasma.StatusPlasma != 7)
		{
			MessageBox.Show("意外熄火或未点火，请在等离子体形成后开始测试！", "提示");
		}
	}

	private void CheckQCSValues(SamplesInfos sample)
	{
		if (Detector.detectorConfig.IsNewBoard)
		{
			RecalculatedAllForNew();
		}
		else
		{
			RecalculatedAll();
		}
		bool flagQC = false;
		foreach (IsotopeInfos isotope in isotopes)
		{
			if (isotope.inter)
			{
				continue;
			}
			double con = (from stat in statistics
				where stat.sampleId == sample.guid && stat.symbol == isotope.symbol
				select stat.avgCon).First();
			double qc = (from qcs in qcsConcentration
				where qcs.sample == sample.guid && qcs.symbol == isotope.symbol
				select qcs.concentration).First();
			if (!(con < qc * qcsPara.lowLimit) && !(con > qc * qcsPara.highLimit))
			{
				continue;
			}
			bool process = false;
			if (qcsPara.method == 0)
			{
				process = true;
			}
			else if (qcsPara.method == 1)
			{
				FormQC dlg = new FormQC();
				DialogResult result = dlg.Check(sample.label, isotope.symbol);
				if (result == DialogResult.Cancel && dlg.Checked)
				{
					return;
				}
				if (result == DialogResult.OK)
				{
					process = true;
				}
			}
			if (!process)
			{
				continue;
			}
			flagQC = true;
			break;
		}
		if (!flagQC)
		{
			return;
		}
		qcsPara.curveNum++;
		int index = samples.IndexOf(sample);
		IEnumerable<SamplesInfos> stdSamples = samples.Where((SamplesInfos stdSample) => stdSample.curveId == 1 && stdSample.status == 1 && (stdSample.type == 0 || stdSample.type == 1 || stdSample.type == 2));
		List<SamplesInfos> samplelist = new List<SamplesInfos>();
		foreach (SamplesInfos stdSample2 in stdSamples)
		{
			IEnumerable<StandardConcentration> stdcons = stdConcentration.Where((StandardConcentration stdcon) => stdcon.sample == stdSample2.guid);
			SamplesInfos newSample = stdSample2.Clone();
			newSample.curveId = qcsPara.curveNum;
			newSample.guid = Scan.sampleIndex++;
			newSample.label = newSample.label + "_" + qcsPara.curveNum;
			samplelist.Add(newSample);
		}
		for (int i = 0; i < samplelist.Count(); i++)
		{
			samples.Insert(index + 1, samplelist[i]);
			index++;
		}
		if (this.sampleChanged != null)
		{
			this.sampleChanged(null, null);
		}
	}

	private bool ExperimentPrepare(SamplesInfos currentSample)
	{
		if (IsRun)
		{
			currentSample.time = DateTime.Now;
			currentSample.status = -1;
			InitResult(currentSample);
			InitSpectrum(currentSample);
		}
		if (this.EventExperiment != null)
		{
			this.EventExperiment(null, new ExperimentEventArgs(currentSample, 0, 0, 0));
		}
		return true;
	}

	public void ExperimentForStableForNew()
	{
		Task.Factory.StartNew(delegate
		{
			bStableFunEnd = false;
			RFManager.rfs.Gate = 0f;
			if (Detector.detectorConfig.IsNewDetector)
			{
				Detector.Instance.msDetectorRF.SetGateNew();
			}
			else
			{
				Detector.Instance.msDetectorRF.SetGate();
			}
			Thread.Sleep(1000);
			if ((Scan.isScan || Scan.isPeakjump) && (!Scan.isSurvey || Scan.isPeakjump))
			{
				List<double> list = new List<double>();
				List<int> list2 = new List<int>();
				double[] array = (Scan.isScan ? scanMass.ToArray() : peakMass.ToArray());
				for (int i = 0; i < array.Count(); i++)
				{
					list.Add(array[i]);
					list2.Add(resolutionType[i]);
				}
				double[] array2 = new double[array.Length];
				int num = 1;
				OutPeakMass.Clear();
				while (!bUptakeAndStableFinished && IsRun)
				{
					Detector.Instance.SetMassAxis(list.ToArray());
					Detector.Instance.SendHopDatas(list.ToArray(), list2.ToArray(), true, false);
					if (!scanEvent.WaitOne(60000))
					{
						Log.InsertLog(Lang.Txt("FormExperLog.Text1"), Lang.Txt("FormExperLog.Text2"), Lang.Txt("FormExperLog.Text3"), (Severity)3);
					}
					else
					{
						for (int j = 0; j < array.Length; j++)
						{
							array2[j] += Detector.msDetectorPara.IntesnsityAnalog[j];
						}
						if (num >= 10)
						{
							break;
						}
						num++;
					}
					Thread.Sleep(10);
				}
				for (int k = 0; k < array.Length; k++)
				{
					if (array2[k] / (double)num * Detector.Instance.dacPAFactors[(int)(array[k] * 100.0)] < Detector.detectorConfig.PaThreshold)
					{
						OutPeakMass.Add(array[k]);
					}
				}
				while (!bUptakeAndStableFinished && IsRun)
				{
					Detector.Instance.SetMassAxis(list.ToArray());
					Detector.Instance.SendHopDatas(list.ToArray(), list2.ToArray(), true, false);
					if (!scanEvent.WaitOne(60000))
					{
						Log.InsertLog(Lang.Txt("FormExperLog.Text1"), Lang.Txt("FormExperLog.Text2"), Lang.Txt("FormExperLog.Text3"), (Severity)3);
					}
					Thread.Sleep(10);
				}
				bStableFunEnd = true;
			}
		});
	}

	public void ExperimentForStable()
	{
		Task.Factory.StartNew(delegate
		{
			bStableFunEnd = false;
			while (!bUptakeAndStableFinished && IsRun)
			{
				if ((!Scan.isScan && !Scan.isPeakjump) || (Scan.isSurvey && !Scan.isPeakjump))
				{
					return;
				}
				List<double> list = new List<double>();
				List<int> list2 = new List<int>();
				double[] array = (Scan.isScan ? scanMass.ToArray() : peakMass.ToArray());
				if (OutPeakMass != null || OutPeakMass.Count() > 0)
				{
					for (int i = 0; i < array.Count(); i++)
					{
						if (!OutPeakMass.Contains(array[i]))
						{
							list.Add(array[i]);
							list2.Add(resolutionType[i]);
						}
					}
				}
				array = list.ToArray();
				Detector.Instance.SetMassAxis(array);
				Detector.Instance.SendHopDatas(array, list2.ToArray(), true, false);
				if (!scanEvent.WaitOne(60000))
				{
					Log.InsertLog(Lang.Txt("FormExperLog.Text1"), Lang.Txt("FormExperLog.Text2"), Lang.Txt("FormExperLog.Text3"), (Severity)3);
				}
				OutPeakMass.AddRange(OutPeakMassBuffer);
				OutPeakMassBuffer.Clear();
			}
			bStableFunEnd = true;
		});
	}

	public void ResetScanevent()
	{
		scanEvent.Set();
	}

	private bool ExperimentSurveyRun(SamplesInfos currentSample)
	{
		int runIndex;
		for (runIndex = 0; runIndex < currentSample.surveys; runIndex++)
		{
			for (int sweepIndex = 0; sweepIndex < Scan.survySweeps; sweepIndex++)
			{
				if (!IsRun)
				{
					return true;
				}
				if (sweepIndex == 0)
				{
					Detector.Instance.SetMassAxis(surveyMass);
				}
				if (this.EventExperiment != null)
				{
					this.EventExperiment(null, new ExperimentEventArgs(currentSample, 1, runIndex + 1, sweepIndex + 1));
				}
				int[] res = new int[surveyMass.Length];
				for (int i = 0; i < res.Length; i++)
				{
					res[i] = 1;
				}
				Detector.Instance.SetHopDatas(surveyMass, (double[])null, res, true, false);
				if (!scanEvent.WaitOne(120000))
				{
					Log.InsertLog(Lang.Txt("FormExperLog.Text1"), Lang.Txt("FormExperLog.Text2"), Lang.Txt("FormExperLog.Text3"), (Severity)3);
					return false;
				}
			}
			if (!IsRun)
			{
				return true;
			}
			if (this.EventExperiment != null)
			{
				this.EventExperiment(null, new ExperimentEventArgs(currentSample, 1, 0, 0));
			}
			SpectrumInfos currentSpectrum = Spectrums.Where((SpectrumInfos spectrum) => spectrum.scanType == 0 && spectrum.sampleId == currentSample.guid && spectrum.scanIndex == runIndex).First();
			ProcessSpectums(currentSpectrum, Scan.survySweeps, 0);
			currentSpectrum.isTest = true;
			OutPeakMass.AddRange(OutPeakMassBuffer);
			OutPeakMassBuffer.Clear();
		}
		return true;
	}

	private bool ExperimentSurveyRunForNew(SamplesInfos currentSample)
	{
		RFManager.rfs.Gate = (float)((double)RFManager.rfs.HVP * 0.23);
		if (Detector.detectorConfig.IsNewDetector)
		{
			Detector.Instance.msDetectorRF.SetGateNew();
			Thread.Sleep(100);
		}
		else
		{
			Detector.Instance.msDetectorRF.SetGate();
			Thread.Sleep(100);
		}
		OutPeakMass.AddRange(surveyMass);
		int runIndex;
		for (runIndex = 0; runIndex < currentSample.surveys; runIndex++)
		{
			Thread.Sleep(5);
			double[] intensityANA = null;
			if (!IsRun)
			{
				return true;
			}
			double[] intensityPC = null;
			double[] intensityANAforPC = null;
			if (!IsRun)
			{
				return true;
			}
			Detector.Instance.SetMassAxis(OutPeakMass.ToArray());
			if (this.EventExperiment != null)
			{
				this.EventExperiment(null, new ExperimentEventArgs(currentSample, 1, runIndex + 1, 1));
			}
			int[] res = new int[OutPeakMass.Count()];
			for (int i = 0; i < res.Length; i++)
			{
				res[i] = 1;
			}
			Detector.Instance.SetHopDatas(OutPeakMass.ToArray(), (double[])null, res, true, false);
			if (!scanEvent.WaitOne(120000))
			{
				Log.InsertLog("全扫", Lang.Txt("FormExperLog.Text2"), Lang.Txt("FormExperLog.Text3"), (Severity)3);
				return false;
			}
			intensityPC = Detector.msDetectorPara.IntesnsityPulse;
			intensityANAforPC = Detector.msDetectorPara.IntesnsityAnalog;
			if (!IsRun)
			{
				return true;
			}
			if (this.EventExperiment != null)
			{
				this.EventExperiment(null, new ExperimentEventArgs(currentSample, 1, 0, 0));
			}
			SpectrumInfos currentSpectrum = Spectrums.Where((SpectrumInfos spectrum) => spectrum.scanType == 0 && spectrum.sampleId == currentSample.guid && spectrum.scanIndex == runIndex).First();
			ProcessSpectumsForNew(currentSpectrum, intensityPC, intensityANAforPC, intensityANA, Scan.survySweeps, 0);
			for (int j = 0; j < currentSpectrum.intensity.Count(); j++)
			{
				double pafactor = Detector.Instance.dacPAFactors[(int)currentSpectrum.mass[j] * 100];
				if (currentSpectrum.intensityPulse[j] < Detector.detectorConfig.PaThreshold && currentSpectrum.intensityAnalog[j] * pafactor < Detector.detectorConfig.PaThreshold)
				{
					currentSpectrum.intensity[j] = currentSpectrum.intensityPulse[j];
				}
				else
				{
					currentSpectrum.intensity[j] = currentSpectrum.intensityAnalog[j] * pafactor;
				}
			}
			currentSpectrum.isTest = true;
		}
		OutPeakMass.Clear();
		return true;
	}

	private bool ExperimentMainRunForNew(SamplesInfos currentSample)
	{
		int runIndex;
		for (runIndex = 0; runIndex < currentSample.mains; runIndex++)
		{
			double[] mass = (Scan.isScan ? scanMass.ToArray() : peakMass.ToArray());
			List<double> mass2 = new List<double>();
			List<int> resolution1 = new List<int>();
			double[] intensityPC = null;
			double[] intensityANAforPC = null;
			if (OutPeakMass != null || OutPeakMass.Count() > 0)
			{
				for (int i = 0; i < mass.Count(); i++)
				{
					if (OutPeakMass.Contains(mass[i]))
					{
						mass2.Add(mass[i]);
						resolution1.Add(resolutionType[i]);
					}
				}
				mass = mass2.ToArray();
				if (mass.Count() > 0)
				{
					RFManager.rfs.Gate = (float)((double)RFManager.rfs.HVP * 0.23);
					if (Detector.detectorConfig.IsNewDetector)
					{
						Detector.Instance.msDetectorRF.SetGateNew();
					}
					else
					{
						Detector.Instance.msDetectorRF.SetGate();
					}
					int count = 0;
					while (IsRun && !(Math.Abs(RFManager.rfs.ReadGate - RFManager.rfs.Gate) < 20f) && count != 30)
					{
						Thread.Sleep(100);
						count++;
					}
					for (int sweepIndex2 = 0; sweepIndex2 < Scan.mainSweeps; sweepIndex2++)
					{
						if (!IsRun)
						{
							return true;
						}
						if (this.EventExperiment != null)
						{
							this.EventExperiment(null, new ExperimentEventArgs(currentSample, 2, runIndex + 1, sweepIndex2 + 1));
						}
						if (sweepIndex2 == 0)
						{
							Detector.Instance.SetMassAxis(mass);
						}
						Detector.Instance.SendHopDatas(mass, dwelltimes, resolution1.ToArray(), true, false);
						if (!scanEvent.WaitOne(60000))
						{
							Log.InsertLog(Lang.Txt("FormExperLog.Text4"), Lang.Txt("FormExperLog.Text2"), Lang.Txt("FormExperLog.Text3"), (Severity)3);
							return false;
						}
					}
					intensityPC = Detector.msDetectorPara.IntesnsityPulse;
					intensityANAforPC = Detector.msDetectorPara.IntesnsityAnalog;
					string intpc1 = "intpc:";
					for (int j = 0; j < Detector.msDetectorPara.IntPCArray.Count; j++)
					{
						intpc1 = Detector.msDetectorPara.IntPCArray[j].ToString() + ",";
					}
					string intANA = "intana:";
					for (int l = 0; l < Detector.msDetectorPara.IntPCArray.Count; l++)
					{
						intANA = Detector.msDetectorPara.IntANAArray[l].ToString() + ",";
					}
					try
					{
						if (bUseAbnormalMethod)
						{
							intensityPC = FindAbnormalData.GetMeanDataList(Detector.msDetectorPara.IntPCArray).ToArray();
							intensityANAforPC = FindAbnormalData.GetMeanDataList(Detector.msDetectorPara.IntANAArray).ToArray();
						}
					}
					catch (Exception ex2)
					{
						Log.InsertLog("ExperimentMainRunForNew", "获取异常数据求平均值", ex2.Message, (Severity)3);
						intensityPC = Detector.msDetectorPara.IntesnsityPulse;
						intensityANAforPC = Detector.msDetectorPara.IntesnsityAnalog;
					}
				}
			}
			if (!IsRun)
			{
				return true;
			}
			double[] intensityANA = null;
			mass2.Clear();
			resolution1.Clear();
			mass = (Scan.isScan ? scanMass.ToArray() : peakMass.ToArray());
			for (int k = 0; k < mass.Count(); k++)
			{
				if (!OutPeakMass.Contains(mass[k]))
				{
					mass2.Add(mass[k]);
					resolution1.Add(resolutionType[k]);
				}
			}
			mass = mass2.ToArray();
			if (mass.Count() > 0)
			{
				RFManager.rfs.Gate = 0f;
				if (Detector.detectorConfig.IsNewDetector)
				{
					Detector.Instance.msDetectorRF.SetGateNew();
				}
				else
				{
					Detector.Instance.msDetectorRF.SetGate();
				}
				int count2 = 0;
				while (IsRun && !(Math.Abs(RFManager.rfs.ReadGate - RFManager.rfs.Gate) < 20f) && count2 != 30)
				{
					Thread.Sleep(100);
					count2++;
				}
				for (int sweepIndex = 0; sweepIndex < Scan.mainSweeps; sweepIndex++)
				{
					if (!IsRun)
					{
						return true;
					}
					if (this.EventExperiment != null)
					{
						this.EventExperiment(null, new ExperimentEventArgs(currentSample, 2, runIndex + 1, sweepIndex + 1));
					}
					if (sweepIndex == 0)
					{
						Detector.Instance.SetMassAxis(mass);
					}
					Detector.Instance.SendHopDatas(mass, resolution1.ToArray(), true, false);
					if (!scanEvent.WaitOne(60000))
					{
						Log.InsertLog(Lang.Txt("FormExperLog.Text4"), Lang.Txt("FormExperLog.Text2"), Lang.Txt("FormExperLog.Text3"), (Severity)3);
						return false;
					}
				}
				intensityANA = Detector.msDetectorPara.IntesnsityAnalog;
				try
				{
					if (bUseAbnormalMethod)
					{
						intensityANA = FindAbnormalData.GetMeanDataList(Detector.msDetectorPara.IntANAArray).ToArray();
					}
				}
				catch (Exception ex)
				{
					Log.InsertLog("ExperimentMainRunForNew", "获取异常数据求平均值", ex.Message, (Severity)3);
					intensityANA = Detector.msDetectorPara.IntesnsityAnalog;
				}
				RFManager.rfs.Gate = (float)((double)RFManager.rfs.HVP * 0.23);
				if (Detector.detectorConfig.IsNewDetector)
				{
					Detector.Instance.msDetectorRF.SetGateNew();
				}
				else
				{
					Detector.Instance.msDetectorRF.SetGate();
				}
			}
			if (!IsRun)
			{
				return true;
			}
			SpectrumInfos currentSpectrum = Spectrums.Where((SpectrumInfos spectrum) => spectrum.scanType == (Scan.isScan ? 1 : 2) && spectrum.sampleId == currentSample.guid && spectrum.scanIndex == runIndex).First();
			ProcessSpectumsForNew(currentSpectrum, intensityPC, intensityANAforPC, intensityANA, Scan.mainSweeps, Scan.isScan ? 1 : 2);
			currentSpectrum.isTest = true;
			ProcessMainRunDatasForNew(currentSample, currentSpectrum, runIndex);
			CalculateSingleResult(currentSample);
			if (this.EventExperiment != null)
			{
				this.EventExperiment(null, new ExperimentEventArgs(currentSample, 6, 0, 0));
			}
			Console.WriteLine("第{0}测试完成时间为：" + DateTime.Now.ToLocalTime().ToString(), runIndex);
		}
		return true;
	}

	private bool ExperimentMainRun(SamplesInfos currentSample)
	{
		int runIndex;
		for (runIndex = 0; runIndex < currentSample.mains; runIndex++)
		{
			double[] mass = (Scan.isScan ? scanMass.ToArray() : peakMass.ToArray());
			List<double> mass2 = new List<double>();
			List<int> resolution1 = new List<int>();
			if (OutPeakMass != null || OutPeakMass.Count() > 0)
			{
				for (int i = 0; i < mass.Count(); i++)
				{
					if (!OutPeakMass.Contains(mass[i]))
					{
						mass2.Add(mass[i]);
						resolution1.Add(resolutionType[i]);
					}
				}
			}
			mass = mass2.ToArray();
			for (int sweepIndex = 0; sweepIndex < Scan.mainSweeps; sweepIndex++)
			{
				if (!IsRun)
				{
					return true;
				}
				if (this.EventExperiment != null)
				{
					this.EventExperiment(null, new ExperimentEventArgs(currentSample, 2, runIndex + 1, sweepIndex + 1));
				}
				if (sweepIndex == 0)
				{
					Detector.Instance.SetMassAxis(mass);
				}
				Detector.Instance.SendHopDatas(mass, dwelltimes, resolution1.ToArray(), true, false);
				if (!scanEvent.WaitOne(60000))
				{
					Log.InsertLog(Lang.Txt("FormExperLog.Text4"), Lang.Txt("FormExperLog.Text2"), Lang.Txt("FormExperLog.Text3"), (Severity)3);
					return false;
				}
			}
			if (!IsRun)
			{
				return true;
			}
			SpectrumInfos currentSpectrum = Spectrums.Where((SpectrumInfos spectrum) => spectrum.scanType == (Scan.isScan ? 1 : 2) && spectrum.sampleId == currentSample.guid && spectrum.scanIndex == runIndex).First();
			ProcessSpectums(currentSpectrum, Scan.mainSweeps, Scan.isScan ? 1 : 2);
			currentSpectrum.isTest = true;
			OutPeakMass.AddRange(OutPeakMassBuffer);
			OutPeakMassBuffer.Clear();
			ProcessMainRunDatas(currentSample, currentSpectrum, runIndex, UsePA);
			CalculateSingleResult(currentSample);
			if (this.EventExperiment != null)
			{
				this.EventExperiment(null, new ExperimentEventArgs(currentSample, 6, 0, 0));
			}
		}
		return true;
	}

	private void Detector_massFinishReceive(object sender, EventArgs e)
	{
		scanEvent.Set();
	}

	private void ProcessSpectums(SpectrumInfos spectrum, int sweeps, int typeid)
	{
		double[] mass = typeid switch
		{
			1 => scanMass.ToArray(), 
			0 => surveyMass.ToArray(), 
			_ => peakMass.ToArray(), 
		};
		int nlenth = mass.Length;
		spectrum.mass = new double[nlenth];
		spectrum.intensityAnalog = new double[nlenth];
		spectrum.intensityPulse = new double[nlenth];
		spectrum.intensity = new double[nlenth];
		Array.Copy(mass, spectrum.mass, nlenth);
		int temp = 0;
		for (int i = 0; i < nlenth; i++)
		{
			if (typeid != 0 && OutPeakMass.Contains(spectrum.mass[i]))
			{
				spectrum.intensityAnalog[i] = double.PositiveInfinity;
				spectrum.intensityPulse[i] = double.PositiveInfinity;
			}
			else
			{
				spectrum.intensityAnalog[i] = Detector.msDetectorPara.IntesnsityAnalog[temp] / (double)sweeps;
				spectrum.intensityPulse[i] = Detector.msDetectorPara.IntesnsityPulse[temp] / (double)sweeps;
				temp++;
			}
		}
	}

	private void ProcessSpectumsForNew(SpectrumInfos spectrum, double[] intensityPC, double[] intensityANAforPC, double[] intensityANA, int sweeps, int typeid)
	{
		double[] mass = typeid switch
		{
			1 => scanMass.ToArray(), 
			0 => surveyMass.ToArray(), 
			_ => peakMass.ToArray(), 
		};
		int nlenth = mass.Length;
		spectrum.mass = new double[nlenth];
		spectrum.intensityAnalog = new double[nlenth];
		spectrum.intensityPulse = new double[nlenth];
		spectrum.intensity = new double[nlenth];
		Array.Copy(mass, spectrum.mass, nlenth);
		int tempPC = 0;
		int tempANA = 0;
		if (typeid == 0)
		{
			for (int i = 0; i < nlenth; i++)
			{
				if (!OutPeakMass.Contains(spectrum.mass[i]))
				{
					spectrum.intensityAnalog[i] = intensityANA[tempANA] / (double)sweeps;
					spectrum.intensityPulse[i] = 0.0;
					tempANA++;
				}
				else
				{
					spectrum.intensityAnalog[i] = intensityANAforPC[tempPC] / (double)sweeps;
					spectrum.intensityPulse[i] = intensityPC[tempPC] / (double)sweeps;
					tempPC++;
					tempANA++;
				}
			}
			return;
		}
		for (int j = 0; j < nlenth; j++)
		{
			if (!OutPeakMass.Contains(spectrum.mass[j]))
			{
				spectrum.intensityAnalog[j] = intensityANA[tempANA] / (double)sweeps;
				spectrum.intensityPulse[j] = 0.0;
				tempANA++;
			}
			else
			{
				spectrum.intensityAnalog[j] = intensityANAforPC[tempPC] / (double)sweeps;
				spectrum.intensityPulse[j] = intensityPC[tempPC] / (double)sweeps;
				tempPC++;
			}
		}
	}

	private void ProcessPADatas(SamplesInfos sample)
	{
		if (sample.status != 1)
		{
			return;
		}
		int runIndex;
		for (runIndex = 0; runIndex < sample.mains; runIndex++)
		{
			IEnumerable<SpectrumInfos> currentSpectrumList = Spectrums.Where((SpectrumInfos spectrum) => spectrum.scanType == (Scan.isScan ? 1 : 2) && spectrum.sampleId == sample.guid && spectrum.scanIndex == runIndex);
			if (currentSpectrumList == null || currentSpectrumList.Count() <= 0 || currentSpectrumList.First().intensity == null)
			{
				continue;
			}
			SpectrumInfos currentSpectrum = currentSpectrumList.First();
			foreach (IsotopeInfos isotope in Isotopes)
			{
				AnalyseInfos cpsResult = Results.Where((AnalyseInfos result) => result.symbol == isotope.symbol && result.sampleId == currentSpectrum.sampleId && result.number == runIndex).First();
				cpsResult.test = true;
				double left = 0.0;
				double right = 0.0;
				if (Scan.isScan)
				{
					IEnumerable<ScanRegions> regions = ScanRegions.Where((ScanRegions region) => region.start <= isotope.mass && region.end >= isotope.mass);
					if (regions != null && regions.Count() > 0)
					{
						left = regions.ElementAt(0).start;
						right = regions.ElementAt(0).end;
					}
				}
				else
				{
					IEnumerable<PeakRegions> regions2 = PeakRegions.Where((PeakRegions region) => region.symbol == isotope.symbol);
					if (regions2 != null && regions2.Count() > 0)
					{
						left = regions2.ElementAt(0).mass - (double)(regions2.ElementAt(0).channels / 2) * regions2.ElementAt(0).separation - 0.1;
						right = regions2.ElementAt(0).mass + (double)(regions2.ElementAt(0).channels / 2) * regions2.ElementAt(0).separation + 0.1;
					}
				}
				if (currentSpectrum.intensityPulse != null && currentSpectrum.intensityPulse.Length != 0)
				{
					cpsResult.IntensityPC = currentSpectrum.intensityPulse.Where((double data, int index) => currentSpectrum.mass[index] >= left && currentSpectrum.mass[index] <= right).Average();
				}
				else
				{
					cpsResult.IntensityPC = 0.0;
				}
				if (currentSpectrum.intensityAnalog != null && currentSpectrum.intensityAnalog.Length != 0)
				{
					cpsResult.IntensityANA = currentSpectrum.intensityAnalog.Where((double data, int index) => currentSpectrum.mass[index] >= left && currentSpectrum.mass[index] <= right).Average();
				}
				else
				{
					cpsResult.IntensityANA = 0.0;
				}
				IEnumerable<double> cpssPC = from result in Results
					where result.symbol == isotope.symbol && result.sampleId == currentSpectrum.sampleId && result.test && !result.exclude
					select result.IntensityPC;
				IEnumerable<double> cpssANA = from result in Results
					where result.symbol == isotope.symbol && result.sampleId == currentSpectrum.sampleId && result.test && !result.exclude
					select result.IntensityANA;
				if (cpssPC != null && cpssPC.Count() > 0)
				{
					IEnumerable<StatisticResults> stat = Statistics.Where((StatisticResults statistic) => statistic.symbol == isotope.symbol && statistic.sampleId == currentSpectrum.sampleId);
					if (stat != null && stat.Count() > 0)
					{
						stat.First().avgUICPSPC = CalculateAverage(cpssPC.ToArray());
						stat.First().avgUICPSANA = CalculateAverage(cpssANA.ToArray());
					}
				}
			}
		}
	}

	private void ProcessMainRunDatasForNew(SamplesInfos csample, SpectrumInfos spectrum, int mainIndex, int UsePA = 0)
	{
		switch (UsePA)
		{
		case 0:
		{
			int i;
			for (i = 0; i < spectrum.intensity.Count(); i++)
			{
				IEnumerable<IsotopeInfos> isotope3 = Isotopes.Where((IsotopeInfos iso) => iso.mass == spectrum.mass[i]);
				double pafactor2 = ((isotope3 != null && isotope3.Count() > 0) ? isotope3.First().PASlope : Detector.Instance.dacPAFactors[(int)(spectrum.mass[i] * 100.0)]);
				if (isotope3.Count() <= 0 || isotope3.First().symbol.Contains("Bkg"))
				{
					spectrum.intensity[i] = spectrum.intensityPulse[i];
				}
				else if (spectrum.intensityPulse[i] < Detector.detectorConfig.PaThreshold && spectrum.intensityAnalog[i] * pafactor2 < Detector.detectorConfig.PaThreshold)
				{
					spectrum.intensity[i] = spectrum.intensityPulse[i];
				}
				else
				{
					spectrum.intensity[i] = spectrum.intensityAnalog[i] * pafactor2;
				}
			}
			break;
		}
		case 1:
		{
			for (int k = 0; k < spectrum.intensity.Count(); k++)
			{
				spectrum.intensity[k] = spectrum.intensityPulse[k];
			}
			break;
		}
		case 2:
		{
			for (int l = 0; l < spectrum.intensity.Count(); l++)
			{
				spectrum.intensity[l] = spectrum.intensityAnalog[l];
			}
			break;
		}
		default:
		{
			int j;
			for (j = 0; j < spectrum.intensity.Count(); j++)
			{
				IEnumerable<IsotopeInfos> isotope2 = Isotopes.Where((IsotopeInfos iso) => iso.mass == spectrum.mass[j]);
				double pafactor = ((isotope2 != null && isotope2.Count() > 0) ? isotope2.First().PASlope : Detector.Instance.dacPAFactors[(int)(spectrum.mass[j] * 100.0)]);
				if (isotope2.Count() <= 0 || isotope2.First().symbol.Contains("Bkg"))
				{
					spectrum.intensity[j] = spectrum.intensityPulse[j];
				}
				else if (spectrum.intensityPulse[j] < Detector.detectorConfig.PaThreshold && spectrum.intensityAnalog[j] * pafactor < Detector.detectorConfig.PaThreshold)
				{
					spectrum.intensity[j] = spectrum.intensityPulse[j];
				}
				else
				{
					spectrum.intensity[j] = spectrum.intensityAnalog[j] * pafactor;
				}
			}
			break;
		}
		}
		foreach (IsotopeInfos isotope in Isotopes)
		{
			AnalyseInfos cpsResult = Results.Where((AnalyseInfos result) => result.symbol == isotope.symbol && result.sampleId == spectrum.sampleId && result.number == mainIndex).First();
			cpsResult.test = true;
			double left = 0.0;
			double right = 0.0;
			if (Scan.isScan)
			{
				IEnumerable<ScanRegions> regions = ScanRegions.Where((ScanRegions region) => region.start <= isotope.mass && region.end >= isotope.mass);
				if (regions != null && regions.Count() > 0)
				{
					left = regions.ElementAt(0).start;
					right = regions.ElementAt(0).end;
				}
			}
			else
			{
				IEnumerable<PeakRegions> regions2 = PeakRegions.Where((PeakRegions region) => region.symbol == isotope.symbol);
				if (regions2 != null && regions2.Count() > 0)
				{
					left = regions2.ElementAt(0).mass - (double)(regions2.ElementAt(0).channels / 2) * regions2.ElementAt(0).separation - 0.1;
					right = regions2.ElementAt(0).mass + (double)(regions2.ElementAt(0).channels / 2) * regions2.ElementAt(0).separation + 0.1;
				}
			}
			if (spectrum.intensity != null && spectrum.intensity.Length != 0)
			{
				cpsResult.intensity = spectrum.intensity.Where((double data, int index) => spectrum.mass[index] >= left && spectrum.mass[index] <= right).Average();
				if (cpsResult.symbol.Contains("Bkg") && cpsResult.intensity > 1.0)
				{
					BlankCalibration blankCalibration = BlankCalibration.Find((BlankCalibration r) => r.Symbol == cpsResult.symbol);
					if (blankCalibration != null)
					{
						cpsResult.intensity = cpsResult.intensity * blankCalibration.Slope + blankCalibration.Intercept;
						if (cpsResult.intensity < 0.0)
						{
							cpsResult.intensity = 0.0;
						}
					}
				}
			}
			else
			{
				cpsResult.intensity = 0.0;
			}
			if (spectrum.intensityPulse != null && spectrum.intensityPulse.Length != 0)
			{
				cpsResult.IntensityPC = spectrum.intensityPulse.Where((double data, int index) => spectrum.mass[index] >= left && spectrum.mass[index] <= right).Average();
			}
			else
			{
				cpsResult.IntensityPC = 0.0;
			}
			if (spectrum.intensityAnalog != null && spectrum.intensityAnalog.Length != 0)
			{
				cpsResult.IntensityANA = spectrum.intensityAnalog.Where((double data, int index) => spectrum.mass[index] >= left && spectrum.mass[index] <= right).Average();
			}
			else
			{
				cpsResult.IntensityANA = 0.0;
			}
			IEnumerable<double> cpss = from result in Results
				where result.symbol == isotope.symbol && result.sampleId == spectrum.sampleId && result.test && !result.exclude
				select result.intensity;
			IEnumerable<double> cpssPC = from result in Results
				where result.symbol == isotope.symbol && result.sampleId == spectrum.sampleId && result.test && !result.exclude
				select result.IntensityPC;
			IEnumerable<double> cpssANA = from result in Results
				where result.symbol == isotope.symbol && result.sampleId == spectrum.sampleId && result.test && !result.exclude
				select result.IntensityANA;
			if (cpss != null && cpss.Count() > 0)
			{
				IEnumerable<StatisticResults> stat = Statistics.Where((StatisticResults statistic) => statistic.symbol == isotope.symbol && statistic.sampleId == spectrum.sampleId);
				if (stat != null && stat.Count() > 0)
				{
					stat.First().avgUICPS = CalculateAverage(cpss.ToArray());
					stat.First().avgUICPSPC = CalculateAverage(cpssPC.ToArray());
					stat.First().avgUICPSANA = CalculateAverage(cpssANA.ToArray());
					stat.First().sdUICPS = CalculateDeviation(cpss.ToArray());
					stat.First().rsdUICPS = stat.First().sdUICPS / stat.First().avgUICPS * 100.0;
				}
			}
		}
	}

	private void ProcessMainRunDatas(SamplesInfos csample, SpectrumInfos spectrum, int mainIndex, int UsePA = 0)
	{
		double BkgPC = 0.0;
		double BkgANA = 0.0;
		int count = 0;
		for (int k = 0; k < spectrum.intensity.Count(); k++)
		{
			if (spectrum.mass[k] == 5.0 || spectrum.mass[k] == 220.0)
			{
				BkgPC += spectrum.intensityPulse[k];
				BkgANA += spectrum.intensityAnalog[k];
				count++;
			}
		}
		BkgPC /= (double)count;
		BkgANA /= (double)count;
		switch (UsePA)
		{
		case 0:
		{
			int i;
			for (i = 0; i < spectrum.intensity.Count(); i++)
			{
				IEnumerable<IsotopeInfos> isotope3 = Isotopes.Where((IsotopeInfos iso) => iso.mass == spectrum.mass[i]);
				double pafactor2 = ((isotope3 != null && isotope3.Count() > 0) ? isotope3.First().PASlope : Detector.Instance.dacPAFactors[(int)(spectrum.mass[i] * 100.0)]);
				double paIntercept2 = isotope3.First().PAIntercept;
				if (isotope3.Count() <= 0)
				{
					spectrum.intensity[i] = spectrum.intensityPulse[i];
				}
				else if (spectrum.intensityPulse[i] < Detector.detectorConfig.PaThreshold && spectrum.intensityAnalog[i] * pafactor2 < Detector.detectorConfig.PaThreshold)
				{
					spectrum.intensity[i] = spectrum.intensityPulse[i];
				}
				else
				{
					spectrum.intensity[i] = spectrum.intensityAnalog[i] * pafactor2 + paIntercept2;
				}
			}
			break;
		}
		case 1:
		{
			for (int m = 0; m < spectrum.intensity.Count(); m++)
			{
				spectrum.intensity[m] = spectrum.intensityPulse[m];
			}
			break;
		}
		case 2:
		{
			for (int l = 0; l < spectrum.intensity.Count(); l++)
			{
				spectrum.intensity[l] = spectrum.intensityAnalog[l];
			}
			break;
		}
		default:
		{
			int j;
			for (j = 0; j < spectrum.intensity.Count(); j++)
			{
				IEnumerable<IsotopeInfos> isotope2 = Isotopes.Where((IsotopeInfos iso) => iso.mass == spectrum.mass[j]);
				double pafactor = ((isotope2 != null && isotope2.Count() > 0) ? isotope2.First().PASlope : Detector.Instance.dacPAFactors[(int)(spectrum.mass[j] * 100.0)]);
				double paIntercept = isotope2.First().PAIntercept;
				if (isotope2.Count() <= 0)
				{
					spectrum.intensity[j] = spectrum.intensityPulse[j];
				}
				else if (spectrum.intensityPulse[j] < Detector.detectorConfig.PaThreshold && spectrum.intensityAnalog[j] * pafactor < Detector.detectorConfig.PaThreshold)
				{
					spectrum.intensity[j] = spectrum.intensityPulse[j];
				}
				else
				{
					spectrum.intensity[j] = spectrum.intensityAnalog[j] * pafactor + paIntercept;
				}
			}
			break;
		}
		}
		foreach (IsotopeInfos isotope in Isotopes)
		{
			AnalyseInfos cpsResult = Results.Where((AnalyseInfos result) => result.symbol == isotope.symbol && result.sampleId == spectrum.sampleId && result.number == mainIndex).First();
			cpsResult.test = true;
			double left = 0.0;
			double right = 0.0;
			if (Scan.isScan)
			{
				IEnumerable<ScanRegions> regions = ScanRegions.Where((ScanRegions region) => region.start <= isotope.mass && region.end >= isotope.mass);
				if (regions != null && regions.Count() > 0)
				{
					left = regions.ElementAt(0).start;
					right = regions.ElementAt(0).end;
				}
			}
			else
			{
				IEnumerable<PeakRegions> regions2 = PeakRegions.Where((PeakRegions region) => region.symbol == isotope.symbol);
				if (regions2 != null && regions2.Count() > 0)
				{
					left = regions2.ElementAt(0).mass - (double)(regions2.ElementAt(0).channels / 2) * regions2.ElementAt(0).separation - 0.1;
					right = regions2.ElementAt(0).mass + (double)(regions2.ElementAt(0).channels / 2) * regions2.ElementAt(0).separation + 0.1;
				}
			}
			if (spectrum.intensity != null && spectrum.intensity.Length != 0)
			{
				cpsResult.intensity = spectrum.intensity.Where((double data, int index) => spectrum.mass[index] >= left && spectrum.mass[index] <= right).Average();
			}
			else
			{
				cpsResult.intensity = 0.0;
			}
			if (spectrum.intensityPulse != null && spectrum.intensityPulse.Length != 0)
			{
				cpsResult.IntensityPC = spectrum.intensityPulse.Where((double data, int index) => spectrum.mass[index] >= left && spectrum.mass[index] <= right).Average();
			}
			else
			{
				cpsResult.IntensityPC = 0.0;
			}
			if (spectrum.intensityAnalog != null && spectrum.intensityAnalog.Length != 0)
			{
				cpsResult.IntensityANA = spectrum.intensityAnalog.Where((double data, int index) => spectrum.mass[index] >= left && spectrum.mass[index] <= right).Average();
			}
			else
			{
				cpsResult.IntensityANA = 0.0;
			}
			IEnumerable<double> cpss = from result in Results
				where result.symbol == isotope.symbol && result.sampleId == spectrum.sampleId && result.test && !result.exclude
				select result.intensity;
			IEnumerable<double> cpssPC = from result in Results
				where result.symbol == isotope.symbol && result.sampleId == spectrum.sampleId && result.test && !result.exclude
				select result.IntensityPC;
			IEnumerable<double> cpssANA = from result in Results
				where result.symbol == isotope.symbol && result.sampleId == spectrum.sampleId && result.test && !result.exclude
				select result.IntensityANA;
			if (cpss != null && cpss.Count() > 0)
			{
				IEnumerable<StatisticResults> stat = Statistics.Where((StatisticResults statistic) => statistic.symbol == isotope.symbol && statistic.sampleId == spectrum.sampleId);
				if (stat != null && stat.Count() > 0)
				{
					stat.First().avgUICPSPC = CalculateAverage(cpssPC.ToArray());
					stat.First().avgUICPSANA = CalculateAverage(cpssANA.ToArray());
					stat.First().avgUICPS = CalculateAverage(cpss.ToArray());
					stat.First().sdUICPS = CalculateDeviation(cpss.ToArray());
					stat.First().rsdUICPS = stat.First().sdUICPS / stat.First().avgUICPS * 100.0;
				}
			}
		}
	}

	private void CalculateISTD(SamplesInfos csample)
	{
		foreach (IsotopeInfos isotope in Isotopes)
		{
			if (!isotope.inter)
			{
				continue;
			}
			int sampleId = -1;
			IEnumerable<SamplesInfos> refers = Samples.Where((SamplesInfos sample) => sample.refer);
			if (refers.Count() > 0)
			{
				sampleId = refers.First().guid;
			}
			else
			{
				sampleId = Samples.ElementAt(0).guid;
			}
			IEnumerable<double> cpss = from result in Results
				where result.symbol == isotope.symbol && result.sampleId == sampleId && result.test && !result.exclude
				select result.intensity;
			if (cpss == null || cpss.Count() <= 0)
			{
				continue;
			}
			double avg = cpss.Average();
			IEnumerable<AnalyseInfos> results = Results.Where((AnalyseInfos result) => result.symbol == isotope.symbol && result.sampleId == csample.guid && result.test);
			foreach (AnalyseInfos result2 in results)
			{
				result2.icps = result2.intensity / avg;
				result2.concentration = result2.icps;
			}
			foreach (StatisticResults stat in Statistics.Where((StatisticResults statistic) => statistic.symbol == isotope.symbol && statistic.sampleId == csample.guid))
			{
				IEnumerable<double> resultsAvg = from result in Results
					where result.symbol == isotope.symbol && result.sampleId == stat.sampleId && result.test && !result.exclude
					select result.intensity / avg;
				if (resultsAvg != null && resultsAvg.Count() > 0)
				{
					StatisticResults statisticResults = stat;
					double avgCon = (stat.avgCPS = CalculateAverage(resultsAvg.ToArray()));
					statisticResults.avgCon = avgCon;
					StatisticResults statisticResults2 = stat;
					avgCon = (stat.sdCPS = CalculateDeviation(resultsAvg.ToArray()));
					statisticResults2.sdCon = avgCon;
					StatisticResults statisticResults3 = stat;
					avgCon = (stat.rsdCPS = stat.sdCPS / stat.avgCPS * 100.0);
					statisticResults3.rsdCon = avgCon;
				}
			}
		}
	}

	private void CalculateUncorrectCPS(SamplesInfos csample)
	{
		foreach (IsotopeInfos isotope in isotopes)
		{
			foreach (StatisticResults stat in Statistics.Where((StatisticResults statistic) => statistic.symbol == isotope.symbol && statistic.sampleId == csample.guid))
			{
				IEnumerable<double> cpss = from result in Results
					where result.symbol == isotope.symbol && result.sampleId == stat.sampleId && result.test && !result.exclude
					select result.intensity;
				if (cpss != null && cpss.Count() > 0)
				{
					stat.avgUICPS = CalculateAverage(cpss.ToArray());
					stat.sdUICPS = CalculateDeviation(cpss.ToArray());
					stat.rsdUICPS = stat.sdUICPS / stat.avgUICPS * 100.0;
				}
			}
		}
	}

	private void CalculateCorrectCPS(SamplesInfos csample)
	{
		foreach (IsotopeInfos isotope in isotopes)
		{
			if (isotope.inter)
			{
				continue;
			}
			double m1 = 1.0;
			double k1 = 1.0;
			double m3 = 1.0;
			double k3 = 1.0;
			IsotopeInfos istdLeft = null;
			IsotopeInfos istdRight = null;
			if (isotope.technique == Lang.Txt("FormStandard.Istd.Technique.None.Text"))
			{
				m1 = (m3 = 1.0);
			}
			else if (isotope.technique == Lang.Txt("FormStandard.Istd.Technique.Interpolation.Text"))
			{
				IEnumerable<IsotopeInfos> std2 = isotopes.Where((IsotopeInfos std) => std.inter && isotope.mass > std.mass);
				if (std2 != null && std2.Count() > 0)
				{
					istdLeft = std2.Last();
				}
				IEnumerable<IsotopeInfos> std3 = isotopes.Where((IsotopeInfos std) => std.inter && isotope.mass < std.mass);
				if (std3 != null && std3.Count() > 0)
				{
					istdRight = std3.ElementAt(0);
				}
			}
			else
			{
				istdLeft = isotopes.Where((IsotopeInfos std) => std.symbol == isotope.technique).First();
			}
			if (istdLeft != null)
			{
				m1 = isotope.mass - istdLeft.mass;
			}
			if (istdRight != null)
			{
				m3 = istdRight.mass - isotope.mass;
			}
			if (istdLeft == null)
			{
				m1 = 1.0;
				m3 = 0.0;
			}
			if (istdRight == null)
			{
				m1 = 0.0;
				m3 = 1.0;
			}
			IEnumerable<AnalyseInfos> cpsResults = Results.Where((AnalyseInfos result) => result.symbol == isotope.symbol && result.sampleId == csample.guid && result.intensity != -1.0);
			foreach (AnalyseInfos cpsResult in cpsResults)
			{
				double m2 = m1;
				double k2 = k1;
				double m4 = m3;
				double k4 = k3;
				if (istdLeft != null)
				{
					IEnumerable<double> k1s = from result in Results
						where result.symbol == istdLeft.symbol && result.sampleId == csample.guid && result.number == cpsResult.number && !result.exclude
						select result.icps;
					if (k1s.Count() > 0)
					{
						k2 = k1s.First();
					}
					else
					{
						m2 = 1.0;
						m4 = 0.0;
					}
				}
				if (istdRight != null)
				{
					IEnumerable<double> k2s = from result in Results
						where result.symbol == istdRight.symbol && result.sampleId == csample.guid && result.number == cpsResult.number && !result.exclude
						select result.icps;
					if (k2s.Count() > 0)
					{
						k4 = k2s.First();
					}
					else
					{
						m2 = 0.0;
						m4 = 1.0;
					}
				}
				double i = (m2 * k4 + m4 * k2) / (m2 + m4);
				cpsResult.icps = cpsResult.intensity / i;
			}
		}
	}

	private void SetUnCalculateInterference(SamplesInfos csample)
	{
		IEnumerable<AnalyseInfos> results = from result in Results
			from isotope in Isotopes
			where result.symbol == isotope.symbol && result.sampleId == csample.guid && isotope.withInterference
			select result;
		foreach (AnalyseInfos result2 in results)
		{
			result2.interferenceCorrected = false;
		}
	}

	private void CalculateInterferenceCPS(SamplesInfos csample)
	{
		foreach (IsotopeInfos isotope in isotopes)
		{
			if (isotope.equations == null)
			{
				continue;
			}
			IEnumerable<AnalyseInfos> cpsResult = Results.Where((AnalyseInfos result) => result.symbol == isotope.symbol && result.sampleId == csample.guid && result.test && !result.exclude);
			foreach (AnalyseInfos result2 in cpsResult)
			{
				result2.icps = InterferenceValue(result2.symbol, result2.sampleId, result2.number);
			}
		}
	}

	private void CalculateStatCPS(SamplesInfos csample)
	{
		foreach (IsotopeInfos isotope in isotopes)
		{
			if (isotope.isInterference || isotope.inter || csample.status == 0)
			{
				continue;
			}
			IEnumerable<double> cpss = from result in Results
				where result.symbol == isotope.symbol && result.sampleId == csample.guid && result.test && !result.exclude
				select result.icps;
			if (cpss != null && cpss.Count() > 0)
			{
				double average = CalculateAverage(cpss.ToArray());
				double sd = CalculateDeviation(cpss.ToArray());
				double rsd = sd / average * 100.0;
				StatisticResults statResult = Statistics.Where((StatisticResults stat) => stat.symbol == isotope.symbol && stat.sampleId == csample.guid).First();
				statResult.avgCPS = average;
				statResult.sdCPS = sd;
				statResult.rsdCPS = rsd;
			}
		}
	}

	private void CalculateSingleResult(SamplesInfos csample)
	{
		CalculateISTD(csample);
		CalculateUncorrectCPS(csample);
		CalculateCorrectCPS(csample);
		SetUnCalculateInterference(csample);
		CalculateInterferenceCPS(csample);
		CalculateStatCPS(csample);
		CalculateCon(csample);
		CalculateSampleBlank(csample);
		CalculateRatio(csample);
	}

	private void CalculateSingleResult(SamplesInfos csample, int mainIndex)
	{
		foreach (IsotopeInfos isotope3 in Isotopes)
		{
			if (!isotope3.inter)
			{
				continue;
			}
			SamplesInfos baseSample = Samples[0];
			IEnumerable<SamplesInfos> baseSamples = Samples.Where((SamplesInfos sample) => sample.refer);
			if (baseSamples.Count() > 0)
			{
				baseSample = baseSamples.First();
			}
			IEnumerable<double> baseIntensitys = from statistic in Statistics
				where statistic.symbol == isotope3.symbol && statistic.sampleId == baseSample.guid
				select statistic.avgUICPS;
			double firstIntensity = double.NaN;
			if (baseIntensitys.Count() > 0 && baseSample.status == 1)
			{
				firstIntensity = baseIntensitys.First();
			}
			IEnumerable<AnalyseInfos> correctResults = Results.Where((AnalyseInfos result) => result.sampleId == csample.guid && result.symbol == isotope3.symbol && (csample == baseSample || result.number == mainIndex) && result.test);
			foreach (AnalyseInfos r2 in correctResults)
			{
				if (!double.IsNaN(firstIntensity))
				{
					r2.icps = r2.intensity / firstIntensity;
					r2.concentration = r2.icps;
				}
				else
				{
					r2.icps = r2.intensity;
					r2.concentration = 0.0;
				}
			}
			IEnumerable<double> allICPS = from result in Results
				where result.symbol == isotope3.symbol && result.sampleId == csample.guid && result.test && !result.exclude
				select result.icps;
			if (allICPS != null && allICPS.Count() > 0)
			{
				StatisticResults stat3 = Statistics.Where((StatisticResults statistic) => statistic.symbol == isotope3.symbol && statistic.sampleId == csample.guid).First();
				stat3.avgCPS = CalculateAverage(allICPS.ToArray());
				stat3.sdCPS = CalculateDeviation(allICPS.ToArray());
				stat3.rsdCPS = stat3.sdCPS / stat3.avgCPS * 100.0;
				stat3.avgCon = stat3.avgCPS;
				stat3.sdCon = stat3.sdCPS;
				stat3.rsdCon = stat3.rsdCPS;
			}
		}
		foreach (IsotopeInfos isotope2 in Isotopes)
		{
			if (isotope2.inter)
			{
				continue;
			}
			AnalyseInfos cps2 = Results.Where((AnalyseInfos result) => result.symbol == isotope2.symbol && result.sampleId == csample.guid && result.number == mainIndex).First();
			double m1 = 1.0;
			double k1 = 1.0;
			double m2 = 1.0;
			double k2 = 1.0;
			IsotopeInfos istdLeft = null;
			IsotopeInfos istdRight = null;
			if (isotope2.technique == Lang.Txt("FormStandard.Istd.Technique.None.Text"))
			{
				k1 = (k2 = 1.0);
			}
			else if (isotope2.technique == Lang.Txt("FormStandard.Istd.Technique.Interpolation.Text"))
			{
				IEnumerable<IsotopeInfos> std2 = isotopes.Where((IsotopeInfos std) => std.inter && isotope2.mass > std.mass);
				if (std2 != null && std2.Count() > 0)
				{
					istdLeft = std2.Last();
				}
				IEnumerable<IsotopeInfos> std3 = isotopes.Where((IsotopeInfos std) => std.inter && isotope2.mass < std.mass);
				if (std3 != null && std3.Count() > 0)
				{
					istdRight = std3.ElementAt(0);
				}
			}
			else
			{
				istdLeft = isotopes.Where((IsotopeInfos std) => std.symbol == isotope2.technique).First();
			}
			if (istdLeft != null)
			{
				m1 = isotope2.mass - istdLeft.mass;
				k1 = (from result in Results
					where result.symbol == istdLeft.symbol && result.sampleId == csample.guid && result.number == mainIndex
					select result.icps).First();
			}
			if (istdRight != null)
			{
				m2 = istdRight.mass - isotope2.mass;
				k2 = (from result in Results
					where result.symbol == istdRight.symbol && result.sampleId == csample.guid && result.number == mainIndex
					select result.icps).First();
			}
			if (istdLeft == null)
			{
				m1 = 1.0;
				m2 = 0.0;
			}
			if (istdRight == null)
			{
				m1 = 0.0;
				m2 = 1.0;
			}
			double i = (m1 * k2 + m2 * k1) / (m1 + m2);
			cps2.icps = cps2.intensity / i;
			IEnumerable<double> allCPS = from result in Results
				where result.symbol == isotope2.symbol && result.sampleId == csample.guid && result.test && !result.exclude
				select result.icps;
			StatisticResults stat2 = Statistics.Where((StatisticResults statistic) => statistic.symbol == isotope2.symbol && statistic.sampleId == csample.guid).First();
			stat2.avgCPS = CalculateAverage(allCPS.ToArray());
			stat2.sdCPS = CalculateDeviation(allCPS.ToArray());
			stat2.rsdCPS = stat2.sdCPS / stat2.avgCPS * 100.0;
			IEnumerable<IsotopeCurve> curves = Curves.Where((IsotopeCurve curve) => curve.symbol == isotope2.symbol && curve.groupId == csample.curveId && curve.calculated);
			if (curves == null || curves.Count() <= 0)
			{
				continue;
			}
			if (curves.ElementAt(0).calculated)
			{
				IEnumerable<AnalyseInfos> conResults = Results.Where((AnalyseInfos result) => result.sampleId == csample.guid && result.symbol == curves.ElementAt(0).symbol);
				List<double> cons = new List<double>();
				foreach (AnalyseInfos con2 in conResults)
				{
					if (con2.icps == double.PositiveInfinity)
					{
						con2.concentration = double.PositiveInfinity;
					}
					else if (curves.ElementAt(0).method == 2)
					{
						con2.concentration = con2.icps / curves.ElementAt(0).k * csample.predilution * csample.volume / csample.mass;
					}
					else if (curves.ElementAt(0).method == 1)
					{
						con2.concentration = (con2.icps - curves.ElementAt(0).b) / curves.ElementAt(0).k;
						con2.concentration = con2.concentration * csample.predilution * csample.volume / csample.mass;
					}
					if (!con2.exclude)
					{
						cons.Add(con2.concentration);
					}
				}
				if (cons != null && cons.Count() > 0)
				{
					double average = CalculateAverage(cons.ToArray());
					double sd = CalculateDeviation(cons.ToArray());
					double rsd = sd / average * 100.0;
					average = ((average < 0.0) ? 0.0 : average);
					sd = ((sd < 0.0) ? 0.0 : sd);
					rsd = ((rsd < 0.0) ? 0.0 : rsd);
					StatisticResults statss = Statistics.Where((StatisticResults statistic) => statistic.symbol == curves.ElementAt(0).symbol && statistic.sampleId == csample.guid).First();
					statss.avgCon = average;
					statss.sdCon = sd;
					statss.rsdCon = rsd;
				}
			}
			IEnumerable<AnalyseInfos> conResult = Results.Where((AnalyseInfos result) => result.sampleId == csample.guid && result.symbol == curves.ElementAt(0).symbol);
			double blkResult = 0.0;
			IEnumerable<StatisticResults> blkStat = Statistics.Where((StatisticResults statistic) => statistic.sampleId == csample.blank && statistic.symbol == curves.ElementAt(0).symbol);
			foreach (AnalyseInfos con in conResult)
			{
				if (blkStat != null && blkStat.Count() > 0)
				{
					blkResult = blkStat.ElementAt(0).avgCon;
				}
				con.concentration -= blkResult;
			}
			Statistics.Where((StatisticResults statistic) => statistic.symbol == curves.ElementAt(0).symbol && statistic.sampleId == csample.guid).First().avgCon -= blkResult;
		}
		foreach (IsotopeRatio isotope in Ratios)
		{
			try
			{
				RatioResults result2 = RatioResults.Where((RatioResults r) => r.SampleId == csample.guid && r.Name == isotope.Name && r.Number == mainIndex).First();
				double numerator = (from cps in Results
					where cps.sampleId == csample.guid && cps.number == mainIndex && cps.symbol == result2.Numerator
					select cps.icps).First();
				double denominator = (from cps in Results
					where cps.sampleId == csample.guid && cps.number == mainIndex && cps.symbol == result2.Denominator
					select cps.icps).First();
				result2.Result = numerator / denominator;
				IEnumerable<double> results = from r in RatioResults
					where r.Name == isotope.Name && r.SampleId == csample.guid
					select r.Result;
				if (results != null && results.Count() > 0)
				{
					RatioStatistics ratioStat = RatioStat.Where((RatioStatistics stat) => stat.Name == isotope.Name && stat.SampleId == csample.guid).First();
					ratioStat.Avg = CalculateAverage(results.ToArray());
					ratioStat.Sd = CalculateDeviation(results.ToArray());
					ratioStat.Rsd = ratioStat.Sd / ratioStat.Avg * 100.0;
				}
			}
			catch
			{
			}
		}
	}

	private void CalculatePA(IsotopeInfos isotope)
	{
		List<double> PCList = new List<double>();
		List<double> AnalogList = new List<double>();
		IEnumerable<string> stdsamples = from ss in Samples
			where ss.type < 3
			select ss.label;
		foreach (StatisticResults stat in Statistics.Where((StatisticResults statistic) => statistic.symbol == isotope.symbol && stdsamples.Contains(statistic.label)))
		{
			if (stat.avgUICPSPC > Detector.detectorConfig.MinPC && stat.avgUICPSPC < Detector.detectorConfig.MaxPC && stat.avgUICPSANA > 0.0)
			{
				PCList.Add(stat.avgUICPSPC);
				AnalogList.Add(stat.avgUICPSANA);
			}
		}
		if (PCList.Count() == 1 && Detector.detectorConfig.IsNewBoard)
		{
			isotope.PASlope = PCList.First() / AnalogList.First();
			isotope.PAIntercept = 0.0;
		}
		if (PCList.Count >= 2)
		{
			double[] kb = LSFit.LineFit(AnalogList.ToArray(), PCList.ToArray(), 0.0, 0.0, false);
			if (kb != null)
			{
				isotope.PASlope = kb[0];
				isotope.PAIntercept = kb[1];
			}
		}
	}

	private void CalculateUncorrectCPS(IsotopeInfos isotope)
	{
		foreach (StatisticResults stat in Statistics.Where((StatisticResults statistic) => statistic.symbol == isotope.symbol))
		{
			IEnumerable<double> cpss = from result in Results
				where result.symbol == isotope.symbol && result.sampleId == stat.sampleId && result.test && !result.exclude
				select result.intensity;
			if (cpss != null && cpss.Count() > 0)
			{
				stat.avgUICPS = CalculateAverage(cpss.ToArray());
				stat.sdUICPS = CalculateDeviation(cpss.ToArray());
				stat.rsdUICPS = stat.sdUICPS / stat.avgUICPS * 100.0;
			}
		}
	}

	private void CalculateISTD(IsotopeInfos isotope)
	{
		if (!isotope.inter)
		{
			return;
		}
		int sampleId = -1;
		IEnumerable<SamplesInfos> refers = Samples.Where((SamplesInfos sample) => sample.refer);
		if (refers.Count() > 0)
		{
			sampleId = refers.First().guid;
		}
		else
		{
			sampleId = Samples.ElementAt(0).guid;
		}
		IEnumerable<double> cpss = from result in Results
			where result.symbol == isotope.symbol && result.sampleId == sampleId && result.test && !result.exclude
			select result.intensity;
		if (cpss == null || cpss.Count() <= 0)
		{
			return;
		}
		double avg = cpss.Average();
		IEnumerable<AnalyseInfos> results = Results.Where((AnalyseInfos result) => result.symbol == isotope.symbol);
		foreach (AnalyseInfos result2 in results)
		{
			result2.icps = result2.intensity / avg;
			result2.concentration = result2.icps;
		}
		foreach (StatisticResults stat in Statistics.Where((StatisticResults statistic) => statistic.symbol == isotope.symbol))
		{
			IEnumerable<double> resultsAvg = from result in Results
				where result.symbol == isotope.symbol && result.sampleId == stat.sampleId && result.test && !result.exclude
				select result.intensity / avg;
			if (resultsAvg != null && resultsAvg.Count() > 0)
			{
				StatisticResults statisticResults = stat;
				double avgCon = (stat.avgCPS = CalculateAverage(resultsAvg.ToArray()));
				statisticResults.avgCon = avgCon;
				StatisticResults statisticResults2 = stat;
				avgCon = (stat.sdCPS = CalculateDeviation(resultsAvg.ToArray()));
				statisticResults2.sdCon = avgCon;
				StatisticResults statisticResults3 = stat;
				avgCon = (stat.rsdCPS = stat.sdCPS / stat.avgCPS * 100.0);
				statisticResults3.rsdCon = avgCon;
			}
		}
	}

	private void CalculateCorrectCPS(IsotopeInfos isotope)
	{
		if (isotope.inter)
		{
			return;
		}
		double m1 = 1.0;
		double k1 = 1.0;
		double m3 = 1.0;
		double k3 = 1.0;
		IsotopeInfos istdLeft = null;
		IsotopeInfos istdRight = null;
		if (isotope.technique == Lang.Txt("FormStandard.Istd.Technique.None.Text"))
		{
			m1 = (m3 = 1.0);
		}
		else if (isotope.technique == Lang.Txt("FormStandard.Istd.Technique.Interpolation.Text"))
		{
			IEnumerable<IsotopeInfos> std2 = isotopes.Where((IsotopeInfos std) => std.inter && isotope.mass > std.mass);
			if (std2 != null && std2.Count() > 0)
			{
				istdLeft = std2.Last();
			}
			IEnumerable<IsotopeInfos> std3 = isotopes.Where((IsotopeInfos std) => std.inter && isotope.mass < std.mass);
			if (std3 != null && std3.Count() > 0)
			{
				istdRight = std3.ElementAt(0);
			}
		}
		else
		{
			istdLeft = isotopes.Where((IsotopeInfos std) => std.symbol == isotope.technique).First();
		}
		if (istdLeft != null)
		{
			m1 = isotope.mass - istdLeft.mass;
		}
		if (istdRight != null)
		{
			m3 = istdRight.mass - isotope.mass;
		}
		if (istdLeft == null)
		{
			m1 = 1.0;
			m3 = 0.0;
		}
		if (istdRight == null)
		{
			m1 = 0.0;
			m3 = 1.0;
		}
		foreach (SamplesInfos sample in samples)
		{
			IEnumerable<AnalyseInfos> cpsResults = Results.Where((AnalyseInfos result) => result.symbol == isotope.symbol && result.sampleId == sample.guid && result.intensity != -1.0);
			foreach (AnalyseInfos cpsResult in cpsResults)
			{
				double m2 = m1;
				double k2 = k1;
				double m4 = m3;
				double k4 = k3;
				if (istdLeft != null)
				{
					IEnumerable<double> k1s = from result in Results
						where result.symbol == istdLeft.symbol && result.sampleId == sample.guid && result.number == cpsResult.number && !result.exclude
						select result.icps;
					if (k1s.Count() > 0)
					{
						k2 = k1s.First();
					}
					else
					{
						m2 = 1.0;
						m4 = 0.0;
					}
				}
				if (istdRight != null)
				{
					IEnumerable<double> k2s = from result in Results
						where result.symbol == istdRight.symbol && result.sampleId == sample.guid && result.number == cpsResult.number && !result.exclude
						select result.icps;
					if (k2s.Count() > 0)
					{
						k4 = k2s.First();
					}
					else
					{
						m2 = 0.0;
						m4 = 1.0;
					}
				}
				double i = (m2 * k4 + m4 * k2) / (m2 + m4);
				cpsResult.icps = cpsResult.intensity / i;
			}
		}
	}

	private void CalculateInterferenceCPS(IsotopeInfos isotope)
	{
		if (isotope.equations == null)
		{
			return;
		}
		foreach (SamplesInfos sample in Samples)
		{
			if (sample.status != 1)
			{
				continue;
			}
			IEnumerable<AnalyseInfos> cpsResult = Results.Where((AnalyseInfos result) => result.symbol == isotope.symbol && result.sampleId == sample.guid);
			foreach (AnalyseInfos result2 in cpsResult)
			{
				result2.icps = InterferenceValue(result2.symbol, result2.sampleId, result2.number);
			}
		}
	}

	private double InterferenceValue(string symbol, int sampleId, int number)
	{
		IsotopeInfos currentIsotope = Isotopes.Find((IsotopeInfos isotope) => isotope.symbol == symbol);
		double icps = 0.0;
		IEnumerable<AnalyseInfos> results = Results.Where((AnalyseInfos result) => result.symbol == symbol && result.sampleId == sampleId && result.number == number);
		if (results != null && results.Count() > 0)
		{
			AnalyseInfos result2 = results.First();
			if (currentIsotope.equations != null && !result2.interferenceCorrected)
			{
				foreach (InterferenceEquation equation in currentIsotope.equations)
				{
					result2.icps += equation.interferenceFactor * InterferenceValue(equation.interferenceSymbol, sampleId, number);
				}
				result2.interferenceCorrected = true;
			}
			icps = result2.icps;
		}
		return icps;
	}

	private void CalculateStatCPS(IsotopeInfos isotope)
	{
		if (isotope.isInterference || isotope.inter)
		{
			return;
		}
		foreach (SamplesInfos sample in Samples)
		{
			if (sample.status == 0)
			{
				continue;
			}
			IEnumerable<double> cpss = from result in Results
				where result.symbol == isotope.symbol && result.sampleId == sample.guid && result.test && !result.exclude
				select result.icps;
			if (cpss != null && cpss.Count() > 0)
			{
				double average = CalculateAverage(cpss.ToArray());
				double sd = CalculateDeviation(cpss.ToArray());
				double rsd = sd / average * 100.0;
				StatisticResults statResult = Statistics.Where((StatisticResults stat) => stat.symbol == isotope.symbol && stat.sampleId == sample.guid).First();
				statResult.avgCPS = average;
				statResult.sdCPS = sd;
				statResult.rsdCPS = rsd;
			}
		}
	}

	private void CalculateSemiCon(IsotopeInfos isotope)
	{
		if (isotope.method != 3)
		{
			return;
		}
		foreach (SamplesInfos sample in samples)
		{
			if (sample.status != 1 || sample.type == 0 || sample.type == 1 || sample.type == 2 || sample.type == 5)
			{
				continue;
			}
			IEnumerable<AnalyseInfos> conResults = Results.Where((AnalyseInfos result) => result.symbol == isotope.symbol && result.sampleId == sample.guid && result.test);
			List<double> cons = new List<double>();
			foreach (AnalyseInfos conResult in conResults)
			{
				conResult.concentration = SemiCalculator.Calculator.Calculate(isotope.mass, conResult.icps, isotope.symbol);
				if (!conResult.exclude)
				{
					cons.Add(conResult.concentration);
				}
			}
			if (cons != null && cons.Count() > 0)
			{
				double average = CalculateAverage(cons.ToArray());
				double sd = CalculateDeviation(cons.ToArray());
				double rsd = sd / average * 100.0;
				average = ((average < 0.0) ? 0.0 : average);
				sd = ((sd < 0.0) ? 0.0 : sd);
				rsd = ((rsd < 0.0) ? 0.0 : rsd);
				StatisticResults stat = Statistics.Where((StatisticResults statistic) => statistic.symbol == isotope.symbol && statistic.sampleId == sample.guid).First();
				stat.avgCon = average;
				stat.sdCon = sd;
				stat.rsdCon = rsd;
			}
		}
	}

	private void CalculateS0(IsotopeInfos isotope)
	{
		if (isotope.inter || isotope.method == 0 || isotope.method == 3)
		{
			return;
		}
		IEnumerable<StatisticResults> stats = from stat in Statistics
			from sample in Samples
			where sample.type == 0 && stat.symbol == isotope.symbol && stat.sampleId == sample.guid
			select stat;
		if (stats == null)
		{
			return;
		}
		for (int i = 0; i < stats.Count(); i++)
		{
			if (stats.ElementAt(i).stdCon != 0.0)
			{
				stats.ElementAt(i).stdCon = 0.0;
			}
		}
	}

	private void CalculateCurve(IsotopeInfos isotope)
	{
		if (isotope.inter || isotope.method == 0)
		{
			return;
		}
		string currentSymbol = isotope.symbol;
		int currentMethod = isotope.method;
		List<StatisticResults> results = new List<StatisticResults>();
		IEnumerable<SamplesInfos> stdsamples = Samples.Where((SamplesInfos sample) => (sample.type == 0 || sample.type == ((currentMethod > 2) ? (currentMethod + 2) : currentMethod)) && sample.status == 1);
		List<int> curvenumbers = new List<int>();
		if (stdsamples != null && stdsamples.ToList().Count > 0)
		{
			foreach (SamplesInfos stdsample in stdsamples)
			{
				if (!curvenumbers.Contains(stdsample.curveId))
				{
					curvenumbers.Add(stdsample.curveId);
				}
			}
		}
		foreach (int id in curvenumbers)
		{
			results.Clear();
			results.AddRange(from result in Statistics
				from sample in Samples
				where result.symbol == currentSymbol && result.sampleId == sample.guid && sample.curveId == id && (sample.type == 0 || sample.type == ((currentMethod > 2) ? (currentMethod + 2) : currentMethod)) && sample.status == 1
				select result);
			if (results == null || results.Count < 2)
			{
				break;
			}
			foreach (StatisticResults stat in results)
			{
				IEnumerable<StandardConcentration> std = StdConcentration.Where((StandardConcentration stdCon) => stdCon.sample == stat.sampleId && stdCon.symbol == Regex.Replace(stat.symbol, "[0-9]", "", RegexOptions.IgnoreCase));
				if (std != null && std.Count() > 0)
				{
					stat.stdCon = std.ElementAt(0).concentration;
				}
			}
			IEnumerable<double> cps1 = from result in results
				where result.include && result.stdCon >= 0.0
				select result.avgCPS;
			IEnumerable<double> con1 = from result in results
				where result.include && result.stdCon >= 0.0
				select result.stdCon;
			if (cps1.Count() <= 1 && con1.Count() <= 1)
			{
				break;
			}
			int points = results.Where((StatisticResults result) => result.stdCon > 0.0).Count();
			double[] kb = null;
			IEnumerable<StatisticResults> blkResult = from result in results
				from sample in Samples
				where sample.type == 0 && result.symbol == isotope.symbol && result.sampleId == sample.guid && result.include
				select result;
			if (isotope.force == 2)
			{
				kb = LSFit.LineFit(con1.ToArray(), cps1.ToArray(), 0.0, 0.0, true);
			}
			else if (isotope.force == 1 && blkResult != null && blkResult.Count() != 0)
			{
				kb = LSFit.LineFit(con1.ToArray(), cps1.ToArray(), blkResult.First().stdCon, blkResult.First().avgCPS, true);
			}
			else if (isotope.weight == 0)
			{
				kb = LSFit.LineFit(con1.ToArray(), cps1.ToArray(), 0.0, 0.0, false);
			}
			else
			{
				List<double> weights = new List<double>(con1);
				for (int i = 0; i < weights.Count(); i++)
				{
					if (weights[i] != 0.0)
					{
						weights[i] = 1.0 / Math.Pow(weights[i], 2.0);
					}
				}
				kb = LSFit.WLineFit(con1.ToArray(), cps1.ToArray(), weights.ToArray(), 0.0, 0.0, false);
			}
			if (kb != null)
			{
				IEnumerable<IsotopeCurve> curves = Curves.Where((IsotopeCurve curve) => curve.symbol == currentSymbol && curve.groupId == id);
				if (curves != null && curves.Count() == 1)
				{
					curves.ElementAt(0).method = currentMethod;
					curves.ElementAt(0).k = kb[0];
					curves.ElementAt(0).b = kb[1];
					curves.ElementAt(0).r = kb[2];
					curves.ElementAt(0).intercept1 = Math.Abs(kb[1]);
					curves.ElementAt(0).intercept2 = Math.Abs(kb[1] / kb[0]);
					curves.ElementAt(0).calculated = true;
					curves.ElementAt(0).points = points;
					Dirty.CurveDirty = true;
				}
			}
		}
	}

	private void CalculateCon(SamplesInfos sample)
	{
		if (sample.status == 0)
		{
			return;
		}
		foreach (IsotopeCurve curve in Curves)
		{
			if (curve.groupId != sample.curveId || !curve.calculated)
			{
				continue;
			}
			IEnumerable<AnalyseInfos> conResult = Results.Where((AnalyseInfos result) => result.sampleId == sample.guid && result.symbol == curve.symbol && result.test);
			List<double> cons = new List<double>();
			foreach (AnalyseInfos con in conResult)
			{
				if (con.icps == double.PositiveInfinity)
				{
					con.concentration = double.PositiveInfinity;
				}
				else if (curve.method == 2)
				{
					con.concentration = con.icps / curve.k * sample.predilution * sample.volume / sample.mass;
				}
				else if (curve.method == 1 || (curve.method == 3 && (sample.type == 0 || sample.type == 5)))
				{
					con.concentration = (con.icps - curve.b) / curve.k;
					con.concentration = con.concentration * sample.predilution * sample.volume / sample.mass;
				}
				if (!con.exclude)
				{
					cons.Add(con.concentration);
				}
			}
			if (cons != null && cons.Count() > 0)
			{
				double average = CalculateAverage(cons.ToArray());
				double sd = CalculateDeviation(cons.ToArray());
				double rsd = sd / average * 100.0;
				StatisticResults stat = Statistics.Where((StatisticResults statistic) => statistic.symbol == curve.symbol && statistic.sampleId == sample.guid).First();
				stat.avgCon = average;
				stat.sdCon = sd;
				stat.rsdCon = rsd;
			}
			else
			{
				StatisticResults stat2 = Statistics.Where((StatisticResults statistic) => statistic.symbol == curve.symbol && statistic.sampleId == sample.guid).First();
				stat2.avgCon = double.NaN;
				stat2.sdCon = double.NaN;
				stat2.rsdCon = double.NaN;
			}
		}
	}

	private void CalculateSampleBlank(SamplesInfos sample)
	{
		if (sample.status == 0)
		{
			return;
		}
		foreach (IsotopeCurve curve in Curves)
		{
			if (curve.groupId != sample.curveId || !curve.calculated)
			{
				continue;
			}
			IEnumerable<AnalyseInfos> conResult = Results.Where((AnalyseInfos result) => result.sampleId == sample.guid && result.symbol == curve.symbol && result.test);
			double blkResult = 0.0;
			IEnumerable<StatisticResults> blkStat = Statistics.Where((StatisticResults statistic) => statistic.sampleId == sample.blank && statistic.symbol == curve.symbol);
			foreach (AnalyseInfos con in conResult)
			{
				if (blkStat != null && blkStat.Count() > 0)
				{
					blkResult = blkStat.ElementAt(0).avgCon;
				}
				con.concentration -= blkResult;
			}
			Statistics.Where((StatisticResults statistic) => statistic.symbol == curve.symbol && statistic.sampleId == sample.guid).First().avgCon -= blkResult;
		}
	}

	private void CalculateRatio(SamplesInfos sample)
	{
		if (sample.status == 0)
		{
			return;
		}
		IEnumerable<RatioResults> results = ratioResults.Where((RatioResults result) => result.SampleId == sample.guid);
		foreach (RatioResults result2 in results)
		{
			IEnumerable<double> numerator = from cps in Results
				where cps.sampleId == sample.guid && cps.symbol == result2.Numerator && cps.number == result2.Number && cps.icps != -1.0
				select cps.icps;
			IEnumerable<double> denominator = from cps in Results
				where cps.sampleId == sample.guid && cps.symbol == result2.Denominator && cps.number == result2.Number && cps.icps != -1.0
				select cps.icps;
			if (numerator.Count() > 0 && denominator.Count() > 0)
			{
				result2.Result = numerator.First() / denominator.First();
				result2.CaliResult = result2.Result;
			}
		}
		IEnumerable<RatioStatistics> statistics = RatioStat.Where((RatioStatistics stat) => stat.SampleId == sample.guid);
		foreach (RatioStatistics stat2 in statistics)
		{
			IEnumerable<double> rs = from result in ratioResults
				where result.Name == stat2.Name && result.SampleId == sample.guid && result.Result != -1.0
				select result.Result;
			if (rs != null && rs.Count() > 0)
			{
				stat2.Avg = CalculateAverage(rs.ToArray());
				stat2.CaliAvg = stat2.Avg;
				stat2.Sd = CalculateDeviation(rs.ToArray());
				stat2.Rsd = stat2.Sd / stat2.Avg * 100.0;
			}
		}
	}

	private void CalculateRatioofSingleSample(SamplesInfos sample)
	{
		if (sample.status == 0)
		{
			return;
		}
		foreach (IsotopeRatio ratio2 in Ratios.FindAll((IsotopeRatio r) => r.Inter))
		{
			IEnumerable<RatioResults> results2 = ratioResults.Where((RatioResults result) => result.SampleId == sample.guid && result.Name == ratio2.Name);
			foreach (RatioResults result3 in results2)
			{
				IEnumerable<double> numerator2 = from cps in Results
					where cps.sampleId == sample.guid && cps.symbol == result3.Numerator && cps.number == result3.Number && cps.icps != -1.0
					select cps.icps;
				IEnumerable<double> denominator2 = from cps in Results
					where cps.sampleId == sample.guid && cps.symbol == result3.Denominator && cps.number == result3.Number && cps.icps != -1.0
					select cps.icps;
				if (numerator2.Count() > 0 && denominator2.Count() > 0)
				{
					result3.Result = numerator2.First() / denominator2.First();
					result3.STDResult = ratio2.STDCon;
					result3.Beta = (result3.STDResult / result3.Result - 1.0) / (ratio2.NumeratorMass - ratio2.DenominatorMass);
					result3.CaliResult = result3.STDResult;
				}
			}
			IEnumerable<RatioStatistics> statistics2 = RatioStat.Where((RatioStatistics stat) => stat.SampleId == sample.guid);
			foreach (RatioStatistics stat3 in statistics2)
			{
				IEnumerable<double> rs2 = from result in ratioResults
					where result.Name == stat3.Name && result.SampleId == sample.guid && result.Result != -1.0
					select result.Result;
				if (rs2 != null && rs2.Count() > 0)
				{
					stat3.Avg = CalculateAverage(rs2.ToArray());
					stat3.STD = ratio2.STDCon;
					stat3.CaliAvg = ratio2.STDCon;
					stat3.Beta = (stat3.STD / stat3.Avg - 1.0) / (ratio2.NumeratorMass - ratio2.DenominatorMass);
					stat3.Sd = CalculateDeviation(rs2.ToArray());
					stat3.Rsd = stat3.Sd / stat3.Avg * 100.0;
				}
			}
		}
		foreach (IsotopeRatio ratio in Ratios.FindAll((IsotopeRatio r) => !r.Inter))
		{
			IEnumerable<RatioResults> results = ratioResults.Where((RatioResults result) => result.SampleId == sample.guid && result.Name == ratio.Name);
			foreach (RatioResults result2 in results)
			{
				IEnumerable<double> numerator = from cps in Results
					where cps.sampleId == sample.guid && cps.symbol == result2.Numerator && cps.number == result2.Number && cps.icps != -1.0
					select cps.icps;
				IEnumerable<double> denominator = from cps in Results
					where cps.sampleId == sample.guid && cps.symbol == result2.Denominator && cps.number == result2.Number && cps.icps != -1.0
					select cps.icps;
				if (numerator.Count() <= 0 || denominator.Count() <= 0)
				{
					continue;
				}
				result2.Result = numerator.First() / denominator.First();
				if (ratio.Technique == "External")
				{
					if (sample.type == 8)
					{
						result2.STDResult = ratio.STDCon;
						result2.CaliResult = ratio.STDCon;
						result2.Beta = result2.STDResult / result2.Result;
						continue;
					}
					double j = -1.0;
					double k2 = -1.0;
					double k4 = -1.0;
					double count2 = 0.0;
					SamplesInfos sample3 = samples.Find((SamplesInfos s) => s.number == sample.number - 1 && s.status != 0);
					SamplesInfos sample5 = samples.Find((SamplesInfos s) => s.number == sample.number + 1 && s.status != 0);
					if (sample3 != null)
					{
						k2 = RatioResults.Find((RatioResults r) => r.Name == ratio.Name && r.Number == result2.Number && r.SampleId == sample3.guid).Beta;
						j += k2;
						count2 += 1.0;
					}
					if (sample5 != null)
					{
						k4 = RatioResults.Find((RatioResults r) => r.Name == ratio.Name && r.Number == result2.Number && r.SampleId == sample5.guid).Beta;
						j += k4;
						count2 += 1.0;
					}
					if (count2 == 0.0)
					{
						result2.CaliResult = result2.Result;
					}
					if (count2 >= 1.0)
					{
						result2.CaliResult = j / count2 * result2.Result;
					}
				}
				else if (ratio.Technique == "None")
				{
					result2.CaliResult = result2.Result;
				}
				else
				{
					result2.STDResult = ratio.STDCon;
					result2.CaliResult = ratio.STDCon;
					result2.Beta = (result2.STDResult / result2.Result - 1.0) / (ratio.NumeratorMass - ratio.DenominatorMass);
				}
			}
			IEnumerable<RatioStatistics> statistics = RatioStat.Where((RatioStatistics stat) => stat.SampleId == sample.guid);
			foreach (RatioStatistics stat2 in statistics)
			{
				IEnumerable<double> rs = from result in ratioResults
					where result.Name == stat2.Name && result.SampleId == sample.guid && result.Result != -1.0
					select result.Result;
				if (rs == null || rs.Count() <= 0)
				{
					continue;
				}
				stat2.Avg = CalculateAverage(rs.ToArray());
				if (ratio.Technique == "External")
				{
					if (sample.type == 8)
					{
						stat2.STD = ratio.STDCon;
						stat2.CaliAvg = ratio.STDCon;
						stat2.Beta = stat2.STD / stat2.Avg;
					}
					else
					{
						double i = -1.0;
						double k1 = -1.0;
						double k3 = -1.0;
						double count = 0.0;
						SamplesInfos sample2 = samples.Find((SamplesInfos s) => s.number == sample.number - 1 && s.status != 0);
						SamplesInfos sample4 = samples.Find((SamplesInfos s) => s.number == sample.number + 1 && s.status != 0);
						if (sample2 != null)
						{
							k1 = RatioStat.Find((RatioStatistics r) => r.Name == ratio.Name && r.SampleId == sample2.guid).Beta;
							i += k1;
							count += 1.0;
						}
						if (sample4 != null)
						{
							k3 = RatioStat.Find((RatioStatistics r) => r.Name == ratio.Name && r.SampleId == sample4.guid).Beta;
							i += k3;
							count += 1.0;
						}
						if (count == 0.0)
						{
							stat2.CaliAvg = stat2.Avg;
						}
						if (count >= 1.0)
						{
							stat2.CaliAvg = i / count * stat2.Avg;
						}
					}
				}
				else if (ratio.Technique == "None")
				{
					stat2.CaliAvg = stat2.Avg;
				}
				else
				{
					stat2.STD = ratio.STDCon;
					stat2.CaliAvg = ratio.STDCon;
					stat2.Beta = (stat2.STD / stat2.Avg - 1.0) / (ratio.NumeratorMass - ratio.DenominatorMass);
				}
				stat2.Sd = CalculateDeviation(rs.ToArray());
				stat2.Rsd = stat2.Sd / stat2.Avg * 100.0;
			}
		}
	}

	private void CalculateRatioofSTDSampleByCalibration(SamplesInfos sample)
	{
		if (sample.status == 0)
		{
			return;
		}
		foreach (IsotopeRatio ratio2 in Ratios.FindAll((IsotopeRatio r) => r.Inter))
		{
			IEnumerable<RatioResults> results2 = ratioResults.Where((RatioResults result) => result.SampleId == sample.guid && result.Name == ratio2.Name);
			foreach (RatioResults result3 in results2)
			{
				IEnumerable<double> numerator2 = from cps in Results
					where cps.sampleId == sample.guid && cps.symbol == result3.Numerator && cps.number == result3.Number && cps.icps != -1.0
					select cps.icps;
				IEnumerable<double> denominator2 = from cps in Results
					where cps.sampleId == sample.guid && cps.symbol == result3.Denominator && cps.number == result3.Number && cps.icps != -1.0
					select cps.icps;
				if (numerator2.Count() > 0 && denominator2.Count() > 0)
				{
					result3.Result = numerator2.First() / denominator2.First();
					result3.STDResult = ratio2.STDCon;
					result3.Beta = (result3.STDResult / result3.Result - 1.0) / (ratio2.NumeratorMass - ratio2.DenominatorMass);
					result3.CaliResult = result3.STDResult;
				}
			}
			IEnumerable<RatioStatistics> statistics2 = RatioStat.Where((RatioStatistics stat) => stat.SampleId == sample.guid);
			foreach (RatioStatistics stat3 in statistics2)
			{
				IEnumerable<double> rs2 = from result in ratioResults
					where result.Name == stat3.Name && result.SampleId == sample.guid && result.Result != -1.0
					select result.Result;
				if (rs2 != null && rs2.Count() > 0)
				{
					stat3.Avg = CalculateAverage(rs2.ToArray());
					stat3.STD = ratio2.STDCon;
					stat3.CaliAvg = ratio2.STDCon;
					stat3.Beta = (stat3.STD / stat3.Avg - 1.0) / (ratio2.NumeratorMass - ratio2.DenominatorMass);
					stat3.Sd = CalculateDeviation(rs2.ToArray());
					stat3.Rsd = stat3.Sd / stat3.Avg * 100.0;
				}
			}
		}
		foreach (IsotopeRatio ratio in Ratios.FindAll((IsotopeRatio r) => !r.Inter))
		{
			IEnumerable<RatioResults> results = ratioResults.Where((RatioResults result) => result.SampleId == sample.guid && result.Name == ratio.Name);
			foreach (RatioResults result2 in results)
			{
				IEnumerable<double> numerator = from cps in Results
					where cps.sampleId == sample.guid && cps.symbol == result2.Numerator && cps.number == result2.Number && cps.icps != -1.0
					select cps.icps;
				IEnumerable<double> denominator = from cps in Results
					where cps.sampleId == sample.guid && cps.symbol == result2.Denominator && cps.number == result2.Number && cps.icps != -1.0
					select cps.icps;
				if (numerator.Count() <= 0 || denominator.Count() <= 0)
				{
					continue;
				}
				result2.Result = numerator.First() / denominator.First();
				if (ratio.Technique == "External")
				{
					result2.STDResult = ratio.STDCon;
					result2.CaliResult = ratio.STDCon;
					result2.Beta = result2.STDResult / result2.Result;
				}
				else if (ratio.Technique == "None")
				{
					result2.CaliResult = result2.Result;
				}
				else
				{
					double Beta2 = ratioResults.Find((RatioResults r) => r.SampleId == sample.guid && r.Name == ratio.Technique && r.Number == result2.Number).Beta;
					result2.CaliResult = (1.0 + (ratio.NumeratorMass - ratio.DenominatorMass) * Beta2) * result2.Result;
				}
			}
			IEnumerable<RatioStatistics> statistics = RatioStat.Where((RatioStatistics stat) => stat.SampleId == sample.guid);
			foreach (RatioStatistics stat2 in statistics)
			{
				IEnumerable<double> rs = from result in ratioResults
					where result.Name == stat2.Name && result.SampleId == sample.guid && result.Result != -1.0
					select result.Result;
				if (rs == null || rs.Count() <= 0)
				{
					continue;
				}
				stat2.Avg = CalculateAverage(rs.ToArray());
				if (ratio.Technique == "External")
				{
					stat2.STD = ratio.STDCon;
					stat2.CaliAvg = ratio.STDCon;
					stat2.Beta = stat2.STD / stat2.Avg;
				}
				else if (ratio.Technique == "None")
				{
					stat2.CaliAvg = stat2.Avg;
				}
				else
				{
					double Beta = ratioStat.Find((RatioStatistics r) => r.SampleId == sample.guid && r.Name == ratio.Technique).Beta;
					stat2.CaliAvg = (1.0 + (ratio.NumeratorMass - ratio.DenominatorMass) * Beta) * stat2.Avg;
				}
				stat2.Sd = CalculateDeviation(rs.ToArray());
				stat2.Rsd = stat2.Sd / stat2.Avg * 100.0;
			}
		}
	}

	private void CalculateRatioOfUnknownByCalibration(SamplesInfos sample)
	{
		if (sample.status == 0)
		{
			return;
		}
		foreach (IsotopeRatio ratio2 in Ratios.FindAll((IsotopeRatio r) => r.Inter))
		{
			IEnumerable<RatioResults> results = ratioResults.Where((RatioResults result) => result.SampleId == sample.guid && result.Name == ratio2.Name);
			foreach (RatioResults result3 in results)
			{
				IEnumerable<double> numerator2 = from cps in Results
					where cps.sampleId == sample.guid && cps.symbol == result3.Numerator && cps.number == result3.Number && cps.icps != -1.0
					select cps.icps;
				IEnumerable<double> denominator2 = from cps in Results
					where cps.sampleId == sample.guid && cps.symbol == result3.Denominator && cps.number == result3.Number && cps.icps != -1.0
					select cps.icps;
				if (numerator2.Count() > 0 && denominator2.Count() > 0)
				{
					result3.Result = numerator2.First() / denominator2.First();
					result3.STDResult = ratio2.STDCon;
					result3.Beta = (result3.STDResult / result3.Result - 1.0) / (ratio2.NumeratorMass - ratio2.DenominatorMass);
					result3.CaliResult = result3.STDResult;
				}
			}
			IEnumerable<RatioStatistics> statistics2 = RatioStat.Where((RatioStatistics stat) => stat.SampleId == sample.guid);
			foreach (RatioStatistics stat3 in statistics2)
			{
				IEnumerable<double> rs2 = from result in ratioResults
					where result.Name == stat3.Name && result.SampleId == sample.guid && result.Result != -1.0
					select result.Result;
				if (rs2 != null && rs2.Count() > 0)
				{
					stat3.Avg = CalculateAverage(rs2.ToArray());
					if (ratio2.Inter)
					{
						stat3.STD = ratio2.STDCon;
						stat3.CaliAvg = ratio2.STDCon;
						stat3.Beta = (stat3.STD / stat3.Avg - 1.0) / (ratio2.NumeratorMass - ratio2.DenominatorMass);
					}
					stat3.Sd = CalculateDeviation(rs2.ToArray());
					stat3.Rsd = stat3.Sd / stat3.Avg * 100.0;
				}
			}
		}
		foreach (IsotopeRatio ratio in Ratios.FindAll((IsotopeRatio r) => !r.Inter))
		{
			IEnumerable<RatioResults> results2 = ratioResults.Where((RatioResults result) => result.SampleId == sample.guid && result.Name == ratio.Name);
			foreach (RatioResults result2 in results2)
			{
				IEnumerable<double> numerator = from cps in Results
					where cps.sampleId == sample.guid && cps.symbol == result2.Numerator && cps.number == result2.Number && cps.icps != -1.0
					select cps.icps;
				IEnumerable<double> denominator = from cps in Results
					where cps.sampleId == sample.guid && cps.symbol == result2.Denominator && cps.number == result2.Number && cps.icps != -1.0
					select cps.icps;
				if (numerator.Count() <= 0 || denominator.Count() <= 0)
				{
					continue;
				}
				result2.Result = numerator.First() / denominator.First();
				if (ratio.Technique == "External")
				{
					double j = -1.0;
					double k2 = -1.0;
					double k4 = -1.0;
					double count2 = 0.0;
					SamplesInfos sample3 = samples.Find((SamplesInfos s) => s.number == sample.number - 1 && s.status != 0);
					SamplesInfos sample5 = samples.Find((SamplesInfos s) => s.number == sample.number + 1 && s.status != 0);
					if (sample3 != null)
					{
						k2 = RatioResults.Find((RatioResults r) => r.Name == ratio.Name && r.Number == result2.Number && r.SampleId == sample3.guid).Beta;
						j += k2;
						count2 += 1.0;
					}
					if (sample5 != null)
					{
						k4 = RatioResults.Find((RatioResults r) => r.Name == ratio.Name && r.Number == result2.Number && r.SampleId == sample5.guid).Beta;
						j += k4;
						count2 += 1.0;
					}
					if (count2 == 0.0)
					{
						result2.CaliResult = result2.Result;
					}
					if (count2 >= 1.0)
					{
						result2.CaliResult = j / count2 * result2.Result;
					}
				}
				else if (ratio.Technique == "None")
				{
					result2.CaliResult = result2.Result;
				}
				else
				{
					double Beta2 = ratioResults.Find((RatioResults r) => r.SampleId == sample.guid && r.Name == ratio.Technique && r.Number == result2.Number).Beta;
					result2.CaliResult = (1.0 + (ratio.NumeratorMass - ratio.DenominatorMass) * Beta2) * result2.Result;
				}
			}
			IEnumerable<RatioStatistics> statistics = RatioStat.Where((RatioStatistics stat) => stat.SampleId == sample.guid);
			foreach (RatioStatistics stat2 in statistics)
			{
				IEnumerable<double> rs = from result in ratioResults
					where result.Name == stat2.Name && result.SampleId == sample.guid && result.Result != -1.0
					select result.Result;
				if (rs == null || rs.Count() <= 0)
				{
					continue;
				}
				stat2.Avg = CalculateAverage(rs.ToArray());
				if (!ratio.Inter && ratio.Technique == "External")
				{
					double i = -1.0;
					double k1 = -1.0;
					double k3 = -1.0;
					double count = 0.0;
					SamplesInfos sample2 = samples.Find((SamplesInfos s) => s.number == sample.number - 1 && s.status != 0);
					SamplesInfos sample4 = samples.Find((SamplesInfos s) => s.number == sample.number + 1 && s.status != 0);
					if (sample2 != null)
					{
						k1 = RatioStat.Find((RatioStatistics r) => r.Name == ratio.Name && r.SampleId == sample2.guid).Beta;
						i += k1;
						count += 1.0;
					}
					if (sample4 != null)
					{
						k3 = RatioStat.Find((RatioStatistics r) => r.Name == ratio.Name && r.SampleId == sample4.guid).Beta;
						i += k3;
						count += 1.0;
					}
					if (count == 0.0)
					{
						stat2.CaliAvg = stat2.Avg;
					}
					if (count >= 1.0)
					{
						stat2.CaliAvg = i / count * stat2.Avg;
					}
				}
				else if (ratio.Technique == "None")
				{
					stat2.CaliAvg = stat2.Avg;
				}
				else
				{
					double Beta = ratioStat.Find((RatioStatistics r) => r.SampleId == sample.guid && r.Name == ratio.Technique).Beta;
					stat2.CaliAvg = (1.0 + (ratio.NumeratorMass - ratio.DenominatorMass) * Beta) * stat2.Avg;
				}
				stat2.Sd = CalculateDeviation(rs.ToArray());
				stat2.Rsd = stat2.Sd / stat2.Avg * 100.0;
			}
		}
	}

	private void ProcessMainRunDatas(SamplesInfos sample, int UsePA)
	{
		if (sample.status != 1 && sample.status != -1)
		{
			return;
		}
		int surveyIndex;
		for (surveyIndex = 0; surveyIndex < sample.surveys; surveyIndex++)
		{
			IEnumerable<SpectrumInfos> currentSpectrumList2 = Spectrums.Where((SpectrumInfos spectrum) => spectrum.scanType == 0 && spectrum.sampleId == sample.guid && spectrum.scanIndex == surveyIndex);
			if (currentSpectrumList2 == null || currentSpectrumList2.Count() <= 0 || currentSpectrumList2.First().intensity == null)
			{
				continue;
			}
			SpectrumInfos currentSpectrum2 = currentSpectrumList2.First();
			switch (UsePA)
			{
			case 0:
			{
				for (int k = 0; k < currentSpectrum2.intensity.Count(); k++)
				{
					double pafactors = Detector.Instance.dacPAFactors[(int)currentSpectrum2.mass[k] * 100];
					if (currentSpectrum2.intensityPulse[k] < Detector.detectorConfig.PaThreshold && currentSpectrum2.intensityAnalog[k] * pafactors < Detector.detectorConfig.PaThreshold)
					{
						currentSpectrum2.intensity[k] = currentSpectrum2.intensityPulse[k];
					}
					else
					{
						currentSpectrum2.intensity[k] = currentSpectrum2.intensityAnalog[k] * pafactors;
					}
				}
				continue;
			}
			case 1:
			{
				for (int j = 0; j < currentSpectrum2.intensity.Count(); j++)
				{
					currentSpectrum2.intensity[j] = currentSpectrum2.intensityPulse[j];
				}
				continue;
			}
			case 2:
			{
				for (int i = 0; i < currentSpectrum2.intensity.Count(); i++)
				{
					currentSpectrum2.intensity[i] = currentSpectrum2.intensityAnalog[i];
				}
				continue;
			}
			}
			for (int l = 0; l < currentSpectrum2.intensity.Count(); l++)
			{
				double pafactors2 = Detector.Instance.dacPAFactors[(int)currentSpectrum2.mass[l] * 100];
				if (currentSpectrum2.intensityPulse[l] < Detector.detectorConfig.PaThreshold && currentSpectrum2.intensityAnalog[l] * pafactors2 < Detector.detectorConfig.PaThreshold)
				{
					currentSpectrum2.intensity[l] = currentSpectrum2.intensityPulse[l];
				}
				else
				{
					currentSpectrum2.intensity[l] = currentSpectrum2.intensityAnalog[l] * pafactors2;
				}
			}
		}
		int runIndex;
		for (runIndex = 0; runIndex < sample.mains; runIndex++)
		{
			IEnumerable<SpectrumInfos> currentSpectrumList = Spectrums.Where((SpectrumInfos spectrum) => spectrum.scanType == (Scan.isScan ? 1 : 2) && spectrum.sampleId == sample.guid && spectrum.scanIndex == runIndex);
			if (currentSpectrumList != null && currentSpectrumList.Count() > 0 && currentSpectrumList.First().intensity != null)
			{
				SpectrumInfos currentSpectrum = currentSpectrumList.First();
				ProcessMainRunDatas(sample, currentSpectrum, runIndex, UsePA);
			}
		}
	}

	private void ProcessMainRunDatasForNew(SamplesInfos sample, int UsePA)
	{
		if (sample.status != 1 && sample.status != -1)
		{
			return;
		}
		int surveyIndex;
		for (surveyIndex = 0; surveyIndex < sample.surveys; surveyIndex++)
		{
			IEnumerable<SpectrumInfos> currentSpectrumList2 = Spectrums.Where((SpectrumInfos spectrum) => spectrum.scanType == 0 && spectrum.sampleId == sample.guid && spectrum.scanIndex == surveyIndex);
			if (currentSpectrumList2 == null || currentSpectrumList2.Count() <= 0 || currentSpectrumList2.First().intensity == null)
			{
				continue;
			}
			SpectrumInfos currentSpectrum2 = currentSpectrumList2.First();
			switch (UsePA)
			{
			case 0:
			{
				for (int k = 0; k < currentSpectrum2.intensity.Count(); k++)
				{
					double pafactors = Detector.Instance.dacPAFactors[(int)currentSpectrum2.mass[k] * 100];
					if (currentSpectrum2.intensityPulse[k] < Detector.detectorConfig.PaThreshold && currentSpectrum2.intensityAnalog[k] * pafactors < Detector.detectorConfig.PaThreshold)
					{
						currentSpectrum2.intensity[k] = currentSpectrum2.intensityPulse[k];
					}
					else
					{
						currentSpectrum2.intensity[k] = currentSpectrum2.intensityAnalog[k] * pafactors;
					}
				}
				continue;
			}
			case 1:
			{
				for (int j = 0; j < currentSpectrum2.intensity.Count(); j++)
				{
					currentSpectrum2.intensity[j] = currentSpectrum2.intensityPulse[j];
				}
				continue;
			}
			case 2:
			{
				for (int i = 0; i < currentSpectrum2.intensity.Count(); i++)
				{
					currentSpectrum2.intensity[i] = currentSpectrum2.intensityAnalog[i];
				}
				continue;
			}
			}
			for (int l = 0; l < currentSpectrum2.intensity.Count(); l++)
			{
				double pafactors2 = Detector.Instance.dacPAFactors[(int)currentSpectrum2.mass[l] * 100];
				if (currentSpectrum2.intensityPulse[l] < Detector.detectorConfig.PaThreshold && currentSpectrum2.intensityAnalog[l] * pafactors2 < Detector.detectorConfig.PaThreshold)
				{
					currentSpectrum2.intensity[l] = currentSpectrum2.intensityPulse[l];
				}
				else
				{
					currentSpectrum2.intensity[l] = currentSpectrum2.intensityAnalog[l] * pafactors2;
				}
			}
		}
		int runIndex;
		for (runIndex = 0; runIndex < sample.mains; runIndex++)
		{
			IEnumerable<SpectrumInfos> currentSpectrumList = Spectrums.Where((SpectrumInfos spectrum) => spectrum.scanType == (Scan.isScan ? 1 : 2) && spectrum.sampleId == sample.guid && spectrum.scanIndex == runIndex);
			if (currentSpectrumList != null && currentSpectrumList.Count() > 0 && currentSpectrumList.First().intensity != null)
			{
				SpectrumInfos currentSpectrum = currentSpectrumList.First();
				ProcessMainRunDatasForNew(sample, currentSpectrum, runIndex, UsePA);
			}
		}
	}

	public void RecalculatedAll(int UsePA = 0)
	{
		if (isInCalculate)
		{
			return;
		}
		isInCalculate = true;
		foreach (IsotopeInfos isotope6 in isotopes)
		{
			CalculatePA(isotope6);
		}
		Parallel.ForEach(Samples, delegate(SamplesInfos sample)
		{
			ProcessMainRunDatas(sample, UsePA);
		});
		Parallel.ForEach(isotopes, delegate(IsotopeInfos isotope)
		{
			CalculateUncorrectCPS(isotope);
		});
		Parallel.ForEach(isotopes, delegate(IsotopeInfos isotope)
		{
			CalculateISTD(isotope);
		});
		foreach (IsotopeInfos isotope5 in isotopes)
		{
			CalculateCorrectCPS(isotope5);
		}
		SetUnCalculateInterference();
		Parallel.ForEach(isotopes, delegate(IsotopeInfos isotope)
		{
			CalculateInterferenceCPS(isotope);
		});
		Parallel.ForEach(isotopes, delegate(IsotopeInfos isotope)
		{
			CalculateStatCPS(isotope);
		});
		foreach (IsotopeInfos isotope4 in isotopes)
		{
			CalculateSemiCon(isotope4);
		}
		foreach (IsotopeInfos isotope3 in isotopes)
		{
			CalculateS0(isotope3);
		}
		foreach (IsotopeInfos isotope2 in Isotopes)
		{
			CalculateCurve(isotope2);
		}
		Parallel.ForEach(Samples, delegate(SamplesInfos sample)
		{
			CalculateCon(sample);
		});
		Parallel.ForEach(Samples, delegate(SamplesInfos sample)
		{
			CalculateSampleBlank(sample);
		});
		Parallel.ForEach(Samples, delegate(SamplesInfos sample)
		{
			CalculateRatio(sample);
		});
		isInCalculate = false;
		Dirty.ResultsDirty = true;
		dirty.CurveDirty = true;
	}

	public void RecalculatedAllForNew(int usePA = 0)
	{
		if (isInCalculate)
		{
			return;
		}
		isInCalculate = true;
		foreach (IsotopeInfos isotope6 in isotopes)
		{
			CalculatePA(isotope6);
		}
		if (switchPA)
		{
			Parallel.ForEach(Samples, delegate(SamplesInfos sample)
			{
				ProcessMainRunDatasForNew(sample, UsePA);
			});
		}
		Parallel.ForEach(isotopes, delegate(IsotopeInfos isotope)
		{
			CalculateUncorrectCPS(isotope);
		});
		Parallel.ForEach(isotopes, delegate(IsotopeInfos isotope)
		{
			CalculateISTD(isotope);
		});
		foreach (IsotopeInfos isotope5 in isotopes)
		{
			CalculateCorrectCPS(isotope5);
		}
		SetUnCalculateInterference();
		Parallel.ForEach(isotopes, delegate(IsotopeInfos isotope)
		{
			CalculateInterferenceCPS(isotope);
		});
		Parallel.ForEach(isotopes, delegate(IsotopeInfos isotope)
		{
			CalculateStatCPS(isotope);
		});
		foreach (IsotopeInfos isotope4 in isotopes)
		{
			CalculateSemiCon(isotope4);
		}
		foreach (IsotopeInfos isotope3 in isotopes)
		{
			CalculateS0(isotope3);
		}
		foreach (IsotopeInfos isotope2 in Isotopes)
		{
			CalculateCurve(isotope2);
		}
		Parallel.ForEach(Samples, delegate(SamplesInfos sample)
		{
			CalculateCon(sample);
		});
		Parallel.ForEach(Samples, delegate(SamplesInfos sample)
		{
			CalculateSampleBlank(sample);
		});
		Parallel.ForEach(Samples, delegate(SamplesInfos sample)
		{
			CalculateRatio(sample);
		});
		isInCalculate = false;
		Dirty.ResultsDirty = true;
		Dirty.CurveDirty = true;
	}

	private void SetUnCalculateInterference()
	{
		Isotopes.ForEach(delegate(IsotopeInfos selectIsotope1)
		{
			selectIsotope1.withInterference = true;
		});
		IEnumerable<AnalyseInfos> results = from result in Results
			from isotope in Isotopes
			where result.symbol == isotope.symbol && isotope.withInterference
			select result;
		foreach (AnalyseInfos result2 in results)
		{
			result2.interferenceCorrected = false;
		}
	}

	private double CalculateAverage(double[] values)
	{
		if (values != null && values.Length != 0)
		{
			return values.Average();
		}
		return double.NaN;
	}

	private double CalculateDeviation(double[] values)
	{
		if (values == null || values.Length == 0)
		{
			return double.NaN;
		}
		if (values.Length == 1)
		{
			return 0.0;
		}
		double sum = 0.0;
		double sum2 = 0.0;
		int counter = 0;
		foreach (double val in values)
		{
			if (!double.IsNaN(val))
			{
				sum += val;
				sum2 += val * val;
				counter++;
			}
		}
		if (counter < 2)
		{
			return double.NaN;
		}
		return Math.Sqrt(((double)counter * sum2 - sum * sum) / (double)counter / (double)(counter - 1));
	}

	public void CalculateCurve(string symbol)
	{
		IEnumerable<IsotopeInfos> isos = Isotopes.Where((IsotopeInfos isotope) => isotope.symbol == symbol);
		if (isos != null && isos.Count() > 0)
		{
			CalculateCurve(isos.ElementAt(0));
		}
	}

	public void ChangeSamleLabel(SamplesInfos sample)
	{
		string label = sample.label;
		IEnumerable<StatisticResults> stats = Statistics.Where((StatisticResults statistic) => statistic.sampleId == sample.guid);
		foreach (StatisticResults stat in stats)
		{
			stat.label = label;
		}
		IEnumerable<AnalyseInfos> results = Results.Where((AnalyseInfos result) => result.sampleId == sample.guid);
		foreach (AnalyseInfos result2 in results)
		{
			result2.label = label;
		}
		IEnumerable<StandardConcentration> stds = StdConcentration.Where((StandardConcentration stdCon) => stdCon.sample == sample.guid);
		foreach (StandardConcentration std in stds)
		{
			std.label = label;
		}
	}

	public void CheckReferSample(int rowIndex = -1)
	{
		if (Samples.Count == 0)
		{
			return;
		}
		if (rowIndex == -1)
		{
			IEnumerable<SamplesInfos> refers = Samples.Where((SamplesInfos sample) => sample.refer);
			if (refers.Count() == 0)
			{
				Samples[0].refer = true;
			}
			return;
		}
		foreach (SamplesInfos sample2 in Samples)
		{
			sample2.refer = false;
		}
		Samples[rowIndex].refer = true;
	}

	private void CheckISTDCurve()
	{
		foreach (IsotopeCurve curve in Curves)
		{
			foreach (IsotopeInfos isotope in Isotopes)
			{
				if (curve.symbol == isotope.symbol)
				{
					if (isotope.inter)
					{
						curve.calculated = false;
					}
					break;
				}
			}
		}
	}

	public void SetResultExclude(string symbol, int sampleId, int num, bool exclude)
	{
		if (symbol != "")
		{
			IEnumerable<AnalyseInfos> results = Results.Where((AnalyseInfos result) => result.symbol == symbol && result.sampleId == sampleId && result.number == num);
			if (results != null && results.Count() > 0)
			{
				results.ElementAt(0).exclude = exclude;
			}
			return;
		}
		IEnumerable<AnalyseInfos> results2 = Results.Where((AnalyseInfos result) => result.sampleId == sampleId && result.number == num);
		if (results2 == null || results2.Count() <= 0)
		{
			return;
		}
		foreach (AnalyseInfos result2 in results2)
		{
			result2.exclude = exclude;
		}
	}

	public void SetUnTested()
	{
		foreach (AnalyseInfos result in Results)
		{
			result.SetUnTested();
		}
		foreach (StatisticResults stat in Statistics)
		{
			stat.SetUnTested();
		}
		foreach (SamplesInfos sample in Samples)
		{
			sample.SetUnTested();
		}
		foreach (IsotopeCurve curve in Curves)
		{
			curve.SetUnTested();
		}
		foreach (RatioResults ratio in RatioResults)
		{
			ratio.SetUnTested();
		}
		foreach (SpectrumInfos spectrum in Spectrums)
		{
			spectrum.SetUnTested();
		}
		Scan.SetUnTested();
		qcsPara.SetUntested();
	}

	public void ChangePA()
	{
		foreach (IsotopeInfos isotope in isotopes)
		{
			isotope.PASlope = Detector.Instance.dacPAFactors[(int)(isotope.mass * 100.0)];
			isotope.PAIntercept = 0.0;
		}
	}

	public bool IsISTD(string symbol)
	{
		foreach (IsotopeInfos isotope in Isotopes)
		{
			if (isotope.symbol == symbol && isotope.inter)
			{
				return true;
			}
		}
		return false;
	}

	public void OnIsotopeChanged()
	{
		dirty.IsotopeInfoDirty = true;
		SortIsotopes();
		if (this.isotopeChanged != null)
		{
			this.isotopeChanged(null, null);
		}
	}

	public void OnSamplerChanged()
	{
		if (this.IsAutoSamplerChangedEvent != null)
		{
			this.IsAutoSamplerChangedEvent(null, null);
		}
	}

	public void OnRefreshChanged()
	{
		if (this.refreshChanged != null)
		{
			this.refreshChanged(null, null);
		}
	}

	public void OnIstdChanged()
	{
		dirty.IsotopeInfoDirty = true;
		CheckISTDCurve();
		if (this.istdChanged != null)
		{
			this.istdChanged(null, null);
		}
	}

	public void OnSampleChanged()
	{
		Dirty.SamplesDirty = true;
		if (this.sampleChanged != null)
		{
			this.sampleChanged(null, null);
		}
	}

	public void OnRatioChanged()
	{
		Dirty.RatiosDirty = true;
		if (this.ratioChanged != null)
		{
			this.ratioChanged(null, null);
		}
	}

	public void OnSampleSelfChanged()
	{
		Dirty.SamplesDirty = true;
		if (this.sampleselfChanged != null)
		{
			this.sampleselfChanged(null, null);
		}
		if (this.sampleChanged != null)
		{
			this.sampleChanged(null, null);
		}
	}

	public void OnMethodChanged()
	{
		if (this.methodChanged != null)
		{
			this.methodChanged(null, null);
		}
	}
}
